article

Saturday, September 4, 2021

ReactJS Simple Select Option Dropdown

ReactJS Simple Select Option Dropdown

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';

class App extends Component {

  constructor(props) {
    super(props);
    this.selectCountry = this.selectCountry.bind(this);
    this.state = {
      countries: [],
      gender: {}
    };
  }
  componentDidMount() {
    this.setState({
      countries: [
        {id: 'AFG', name: 'Afghanistan'},
        {id: 'DZ', name: 'Algeria'},
        {id: 'ALB', name: 'Albania'},
        {id: 'PH', name: 'Philippines'},
        {id: 'US', name: 'United States'}
      ]
    });

    this.setState({
      gender: {
        "Male": "Male",
        "Female": "Female"
      }
    });
  }

  selectCountry = (e) => {
    let idx = e.target.value;
    alert(idx)
  }
  render() {
    const { countries } = this.state;
    const { gender } = this.state;

    let countriesList = countries.length > 0
    	&& countries.map((item, i) => {
      return (
        <option key={i} value={item.id}>{item.name}</option>
      )
    }, this);

    let genderList = Object.keys(gender).map((k) => {
      return (
        <option key={k} value={k}>{gender[k]}</option>
      )
    }, this);

    return (
      <div className="container">
        <div className="row">
          <h1>ReactJS Simple Select Option Dropdown</h1>
          <form>
          <div className="form-group">
            <label>Country: </label>
            <select className="form-select" onChange={this.selectCountry}>
              {countriesList}
            </select>
          </div>
          <div className="form-group">
          <label>Gender: </label>
            <select className="form-select">
              {genderList}
            </select>
          </div>
          </form>
        </div>
      </div>
    );
  }
}export default App;

Related Post