简体   繁体   中英

How do I set the default value of a <select> element in React?

I have a plain old <select> element that iterates through a list of options:

<select onChange={(event) => this.setState({selectedOption: event.target.value }) }>
{
    this.state.options.map(option => <option key={option.label} value={option.value}>{option.value}</option>)
}
</select>

Since I'm fetching the list of options and the selected item is being fetched via AJAX, I'm doing this -- but it doesn't work either:

<option key={option.label} selected={option.value === this.state.selectedOption} value={option.value}>{option.label}</option>

How do I set the default option (without using an external library, creating custom component)?

Edit: options is just a list of objects:

[
    {label: 'foo', value: 'fooValue'},
    {label: 'bar', value: 'barValue'},
]

All defaults can be set in the constructor...

class ComponentName extends React.Component {
    constructor() {
        super(props);
        this.state = { selectedOption: "My Default Select Value" }
    }
}

After that, let's look at your onChange handler, which is setup well here: you are correctly setting the state to the value of selected option. Assuming that this is JSX that gets returned from render() , then the only thing you are missing is to set the value attribute of the component...

<select
    value={this.state.selectedOption}
    onChange={(event) => this.setState({selectedOption: event.target.value }) }
>
{
    this.state.options.map(option => <option key={option.label} value={option.value}>{option.value}</option>)
}
</select>

Take a look at the official docs (Source: ReactJS.org: Forms )...

React, instead of using this selected attribute, uses a value attribute on the root select tag. This is more convenient in a controlled component because you only need to update it in one place.

 Pick your favorite flavor: <select value={this.state.value} onChange={this.handleChange}>

The reason selected attribute is not working is probably because the default value of this.state.selectedOption is not set. In order to fix this, you can set the value of selectedOption within the constructor.

class ComponentName extends React.Component {
    constructor() {
        ...
        this.state = { selectedOption: "<default_option>" }
        ...
    }
}

In case you don't know the default value that should be set beforehand, then, you can use setState() later to change the value of selectedOption .

Example: https://codesandbox.io/s/funny-feynman-1b6g1?file=/src/App.js

function myAjaxFunction(...) {
    let default_value = ...

    this.setState({
        selectedOption: default_value
    });

    ...
}

PS: This answer assumes that you are using class-based component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM