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.
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.
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
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With