Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJs Select add default value

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
    });
}
like image 686
IntoTheDeep Avatar asked Aug 14 '16 15:08

IntoTheDeep


People also ask

How to set the default value of the selected value in react?

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.

How do I customize react-select?

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.

Does react-select V2 now only accept objects as values?

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.

How to set the default value in the Select Menu?

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.


1 Answers

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?

like image 86
Phil Bellamy Avatar answered Oct 11 '22 23:10

Phil Bellamy