11

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
    });
}
IntoTheDeep
  • 4,027
  • 15
  • 39
  • 84

2 Answers2

11

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?

Community
  • 1
  • 1
Phil Bellamy
  • 310
  • 3
  • 11
2

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    ];
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {
        setStatusValue(e.value);
    }

return(
<>
<Select options={statusOptions} defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} onChange={handleStatusChange} value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
Joomler
  • 2,610
  • 3
  • 30
  • 37