Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load options of a select box dynamically based on value of another select box in react

Tags:

html

reactjs

I m trying to create 2 select boxes in which options of 1st select box are fixed but the second ones change based on the selected value of first div.

eg: 1st Select:

<select>
    <option>Integers</option>
    <option>Alphabets</option>
</select>

Then if Integers is selected in 1st select then I want integers 1 to 10 as options in the 2nd select box. But if Alphabets is selected the a to z should come in options of the second select box.

like image 768
DadyByte Avatar asked Jan 03 '18 11:01

DadyByte


People also ask

How do you pass select option value in React?

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element.


1 Answers

You can create a lookup table object that holds both integers and Alphabets with each has a relevant key.
Then in one select you update the state with selected key and in the other select you render the options correspond to the selected key.


Here is a running example:

const lookup = {
  "int": [
    { id: '1', text: '1' },
    { id: '2', text: '2' },
    { id: '3', text: '3' },
    { id: '4', text: '4' },
    { id: '5', text: '5' }
  ],
  "abc": [
    { id: 'a', text: 'a' },
    { id: 'b', text: 'b' },
    { id: 'c', text: 'c' },
    { id: 'd', text: 'd' },
    { id: 'e', text: 'e' }
  ]
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataValue: 'int'
    }
  }

  onChange = ({ target: { value } }) => {
    this.setState({ dataValue: value });
  }

  render() {
    const { dataValue } = this.state;
    const options = lookup[dataValue];
    return (
      <div>
        <select onChange={this.onChange}>
          <option value="int">Integers</option>
          <option value="abc">Alphabets</option>
        </select>
        <hr />
        <select>
          {options.map(o => <option key={o.id} value={o.id}>{o.text}</option>)}
        </select>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<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="root"></div>
like image 148
Sagiv b.g Avatar answered Oct 04 '22 05:10

Sagiv b.g