ReactJs Select add default value

20,551

Solution 1

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?

Solution 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 />
</>
)
Share:
20,551
IntoTheDeep
Author by

IntoTheDeep

Like most of us, I was born. Some years later I created my first website. I love traveling and I'm an espresso snob. I share my knowledge about the web with my students in college and I would love to teach at your company. For those that are interested in old school paper, I have a bachelor degree in IT and a master degree in commercial sciences. Yup, that last one is for making sure I earn more than I spend. I love running, I even made an app for making running with others easier. If you ever feel like going for a run and talk shop, I’m cool with that.

Updated on July 15, 2022

Comments

  • IntoTheDeep
    IntoTheDeep almost 2 years

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