Conditionally disabled select option in React
After a couple of time, I finally fixed the issue.
It seems that in React to use selected
attribute on the HTML tag is not recommended. The best ways to set a default value is to use defaultValue
If you use it, it will throw an error in development and keep quiet in production.
More info can be found here
How to avoid such error
Step one
- Give default value to HTML
select
Tag
- Give default value to HTML
<select
name="originId"
defaultValue="Choose-origin"
>
- Give
option
tag thevalue
which is equal todefaultValue
ofselect
<option
value="Choose-origin" // normally in VanillaJS you would use "selected"
disabled
>Choose origin</option>
- Remember to disable the
option
tags so that you deny the user to click it.
Thanks, to @Neo Choi and @Bernard Leech for help.
This should work:
<option
value=""
disabled={this.props.defaultDisabled}
>
{this.props.defaultLabel}
</option>
You missed a .props
. And you can also use null
instead of false
.
<option value="" disabled={this.props.defaultDisabled ? true : null} >{this.props.defaultLabel}</option>