Reputation: 53
[edit] This was due to my own confusion, apologies.
Setting the selected
property on <option>
elements in JSX works perfectly, but it causes React the throw a warning:
Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>.
Setting defaultValue
on the parent <select>
element causes the value
of the <select>
to default to that setting, but it does not set the default selected <option>
. So this throws what the user sees and what is actually selected out of sync.
Setting the value
property on the parent <select>
element forces me to then add an onChange handler, set the value in component state, and write a bunch of extra code all to accomplish what simply setting selected
on the <option>
elements does with a single word.
Does anybody know why React throws this warning? I don't want to write a bunch of additional code to remove a warning that doesn't seem to map to reality. It works fine as far as I can tell, so why shouldn't I use it?
Upvotes: 4
Views: 9636
Reputation: 1051
Here's the React documentation to go along with that warning: https://facebook.github.io/react/docs/forms.html
If you do it the way they're suggesting, you could render your <SELECT>
component with a "value" property. Then you would need to write a handler function for the onChange event, to make sure that the component re-renders to reflect the user's changed selection.
If you tried to manage this flow of information at the level of the individual <OPTION>
element, I think you'd have the same challenges, and then some. For example, let's say option A is selected on page load. Then the user selects option B. Option B would need to re-render to appear selected, and option A would need to re-render to appear unselected. For the onClick event on option B to trigger a change on option A, the information would have to be passed from option B to the parent Select element, and then down to the option A element.
That React documentation also talks about an "uncontrolled" <SELECT>
element, which I think means that it would render once initially (and you could specify a defaultValue for it, but React wouldn't keep re-rendering it in realtime.
Upvotes: 4