TheoG TheoG - 15 days ago 6
React JSX Question

(React) Dynamic dropdown box examples. HowTo?

Can anyone point me in the direction of any dynamic React drop-down box examples?

I wish to implement drop-down functionality, which will take the result of a primary drop-down selection, to determine the output of a secondary drop-down list. For example, selecting 'London' from a primary drop-down list, will populate a secondary drop-down box with regions (boroughs) within London.

I'm planning to populate the drop-down boxes by selecting data from a firebasedb.

Answer

You can create the list of options of select box in react dynamically from your props or state. Run the snippet below for an example on how this could look like.

Also check out react's docs for more info on <select> elements in react.

class MyForm extends React.Component {
  constructor(props) {
    super(props)
    
    this.handleFirstLevelChange = this.handleFirstLevelChange.bind(this)
    this.handleSecondLevelChange = this.handleSecondLevelChange.bind(this)
    
    // Prepopulate with the first item for each level
    this.state = {
      firstLevel: Object.keys(props.options)[0],
      secondLevel: Object.keys(props.options)[0][0]
    }
  }
  
  handleFirstLevelChange(event) {
    this.setState({firstLevel: event.target.value});
  }
  
  handleSecondLevelChange(event) {
    this.setState({secondLevel: event.target.value});
  }
  
  render() {
    const renderOption = item => <option value={item}>{item}</option>

    const firstLevelOptions = Object.keys(this.props.options).map(renderOption)
    const secondLevelOptions = this.props.options[this.state.firstLevel].map(renderOption)
    
    return (
      <div>
        <p>
          <select onChange={this.handleFirstLevelChange} value={this.state.firstLevel}>
            {firstLevelOptions}
          </select>
        </p>
        <p>
          <select onChange={this.handleSecondLevelChange} value={this.state.secondLevel}>
            {secondLevelOptions}
          </select>
        </p>
      </div>
    )
  }
}

const options = {
  "USA": ["New York", "San Francisco"],
  "Germany": ["Berlin", "Munich"]
}

ReactDOM.render(
  <MyForm options={options} />,
  document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></div>