I want to store select default value if user not touch it in ReactJs. How is that possible?
<select onChange={this.valSelected.bind(this)}>
{currencies.map(function(name, index){
return <option value={name}>{name}</option>;
})}
</select>
and
valSelected(event){
this.setState({
valSelected: event.target.value
});
}
All controlled input components in React maintain the user’s selected value in the state. The <select> element, if it’s controlled, must have a value attribute set to the selected value in the state. To set the default value of the <select> element, you can use the defaultValue attribute in React.
The react-select is a library that provides a custom Select component and gives you the option to customize its look, functionality, and more. To customize the options, you must provide an array of objects with key-value pairs; for instance, the options from our previous example are below.
If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value, defaultValue, etc. That is, try using value= { {value: 'one', label: 'One'}}, instead of just value= {'one'}. I was having a similar error.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. You can use an attribute defaultValue to set the default value in the Select menu If none option is integrated with this attribute first option is selected by default.
You can just add a value property to the select element, set by your state.
<select value={this.state.valSelected} onChange={this.valSelected.bind(this)}>
{currencies.map(function(name, index){
return <option value={name}>{name}</option>;
})}
</select>
This is described here in the react docs: Doc Link
Then set a default state for the component, either in the constructor or with getInitialState: What is the difference between using constructor vs getInitialState in React / React Native?
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