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
    });
}

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?

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 />
</>
)

Comments

Your Answer

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.