React select with value null

When setting the value for your select component, you will have to convert null to ''; and when receiving the value from your component, you will have to convert '' to null. A simple example:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.state = { selected: null };
    }

    render() {
        return <div>
            <select
                className="input form-control"
                onChange={e => this.setState({ selected: e.target.value || null })}
                value={this.state.selected || ''}>
                <option value=""></option>
                <option value="1">cook dinner</option>
                <option value="2">do dishes</option>
                <option value="3">walk dog</option>
            </select>
            <input type="button" onClick={() => this.setState({ selected: null })} value="Reset" />
        </div>
    }
}

This works assuming that your ids are always truthy: e.target.value || null will convert the selected empty string to null; and this.state.selected || '' will convert your null state to an empty string. If your ids can be falsey (for example the number 0), you will need a more robust conversion.

See Fiddle here.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)