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
 });
}
asked Aug 14, 2016 at 15:12

2 Answers 2

12

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?

answered Nov 22, 2016 at 11:49
Sign up to request clarification or add additional context in comments.

Comments

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 />
</>
)
answered Sep 28, 2020 at 2:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.