react: Should React warn when controlled
Consider the following example (live at http://www.webpackbin.com/Vk0Q_FqmZ with React 15.0.1):
const MySelect = (props) => (
<select value={this.props.value} onChange={this.props.onChange}>
<option value="fruit">banana</option>
<option value="vegetable">broccoli</option>
<option value="fruit">orange</option>
<option value="vegetable">tomato</option>
</select>
);
class App extends React.Component {
constructor() {
super()
this.state = {}
this.onSelectChange = this.onSelectChange.bind(this)
}
onSelectChange(e) {
this.setState({ selectedValue: e.target.value })
}
render() {
return <MySelect
value={this.state.selectedValue}
onChange={this.onSelectChange}
/>
}
}
HTML itself doesn’t seem to have any problems with duplicate values in the <select> tag. As you can see in the example above, there are semantically valid reasons you might want to do this.
But this controlled component example makes it impossible to select e.g. “orange” or “tomato”: the selection will be forced to the first matching value.
I thought about a solution that stores both the selectedValue and the selectedIndex, but react-dom’s <select> does not take any sort of index prop, so I’d have to manipulate the internal DOM node, which I’m sure is bad form.
React could be enhanced to take a selectedIndex, but I foresee problems with single source of truth.
The fruit/vegetable example is a bit contrived, and there may not be many real-world scenarios you would want to do this in. My gut feeling is this should be a warning so developers (like me) don’t paint themselves into a corner trying to support this case.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 8
- Comments: 16 (4 by maintainers)
Why should it warn instead of selecting proper option as DOM does? http://jsbin.com/mesurekaso/edit?html,output
I think it’s better to have consistency
This is a bug in React. We shouldn’t warn, we should fix
<select>behaviour to eliminate inconsistency cc @jimfb