I have a problem where state object needs to be set after options have been generated and not only when onChange
is triggered upon selection change. I have the following state:
this.state = {
trailers: [],
createTrailer: "",
}
This populates based on what is selected in my <select>
element with an onChange
handler:
handleStateChange = (event) => {
this.setState({[event.target.name]: event.target.value})
}
It works fine, however,the options get populated from a GET request in componentDidMount()
and what gets selected by default when it populates does not change the state. Thus, the createTrailer
state stays blank until I actually select something.
How can I populate my state with the default option in a scenario where I don't change my selection but leave the default one? Because at the moment if I leave it obviously that does not work with my form submission as a blank value gets submitted.
<b><label>Choose:</label></b>
<select className="form-control" name="createTrailer" onChange={this.handleStateChange} id="trailerSelect">
{
trailers.length
? trailers.map(trailer => <option key={trailer._id} value={trailer._id}>{trailer.trailerNum}</option>)
: null
}
</select>
EDIT: Duplicate question does not answer my question, it explains how to handle state changes with <select>
and I have done all of that correctly.