Whats the approved way to create select element in react, which is two way bound with the prop of selection containing ponent? The default selection should be the present attribute of the prop (may be generated, because the value is arbitrary, and on selection the prop attribute should reflect the selection. Also, it should be possible to write the value directly to the selection field.
Whats the approved way to create select element in react, which is two way bound with the prop of selection containing ponent? The default selection should be the present attribute of the prop (may be generated, because the value is arbitrary, and on selection the prop attribute should reflect the selection. Also, it should be possible to write the value directly to the selection field.
Share Improve this question asked Jun 29, 2016 at 9:19 Tuomas ToivonenTuomas Toivonen 23.5k51 gold badges144 silver badges243 bronze badges 1- Can you add more specifics on your case? From your question, it's not clear what you need. Have you looked at facebook.github.io/react/docs/forms.html#why-select-value to use it as a foundation of your custom select element? – Gosha A Commented Jun 29, 2016 at 9:40
2 Answers
Reset to default 4I add the options to an array on state and then map overthem, try this code
import React, { Component } from 'react'
class SelectExample extends Component {
constructor() {
super()
this.state = {
options: ['One', 'Tow', 'Three'],
selectedOption: 'One',
}
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value,
})
}
render() {
return (
<select name='selectedOption' onChange={this.handleChange}>
{this.state.options.map(i => i == this.state.selectedOption ? (
<option value={i} selected>
{i}
</option>
) : (<option value={i}>{i}</option>) )}
</select>
)
}
}
There isn't an "approved" way as such, but you should note a couple of things:
The change event is triggered on the element, not the element.
Controlled and uncontrolled ponents
defaultValue
are set differently.
This is a generic example of a controlled dropdown menu
var MyDropdown = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
<div>
<select id="fruit" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Apples">Apples</option>
<option value="Mangoes">Mangoes</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
React.render(<MyDropdown />, document.body);
and here's a working demo.