TheoG TheoG - 8 months ago 67
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 Source

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) {
    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) {
  handleSecondLevelChange(event) {
  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 (
          <select onChange={this.handleFirstLevelChange} value={this.state.firstLevel}>
          <select onChange={this.handleSecondLevelChange} value={this.state.secondLevel}>

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

  <MyForm options={options} />,
<script src=""></script>
<script src=""></script>

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