React Select OnChange Not Called When Options Change
I have a <select>
in my component where the list of options is filtered depending on state and is initialized with nothing.
render() {
<select value={this.state.time} className='input' onChange={e => this.setState({time: e.target.value})} disabled={!this.state.date} >
{ availableDates.filter(d => moment(d).format('YYYY-MM-DD') === this.state.date).map(d =>
<option key={d} value={moment(d).format('H:mm')}>{moment(d).format('H:mm')}</option>
)}
</select>
}
It means that as long as this.state.date
is null
, the select
has no option
. Then when date
is set, there is most of the time only one value. On the display, it becomes immediately selected.
But onChange
is not triggered, and never is (even if I explicitly select the value).
Is this the expected behavior? Somehow, I'd say the value changed so the onChange
should be triggered, shouldn't it?
Besides, how can I make it work anyway? I need the select to be displayed even without options ...
Answer
Yes, the state value was changed, but the select's change event, in fact, wasn't, it just got re-rendered with the new value.
Also, most browsers don't trigger the change event when re-selecting the current value (but if I recall it correctly, some old IEs do).
Hence, I believe that it's the expected behavior.
To make it work, in the code that sets the date state, it could also set the default time value. That makes sense, because you want to set the time when the date has changed.
As a side note, depending on how you'll implement that, you may want to take a look into uncontrolled components.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?