So, I was just wondering if I absolutely need to have a onChange event handler on a select component in React?
I have a prop passing in the default value on the option I want selected. It works no problem if I have:
<select
value={this.props.defaultValue}
>
<option value="a">A</option>
<option value="b">B</option>
</select>
Except, it is static as I am sure you are familiar with the error:
Warning: Failed form propType: You provided a `value` prop to a form field without an `onChange` handler.
This will render a read-only field.
As I am getting the value using Jquery, I don't need a state or any passing between child and parent...
Is there a simple way to allow the select to get a default value from props and still operate as a normal select where changing an option changes the value I can grab with jquery, or do I have to have a state, and a onChange handler?
Thanks!
What I have already tried:
<select
defaultValue={this.props.defaultValue} // just returns the first option
>
<options etc.>
</select>
Also, I would rather not use an external package like React-Select... I just want to have a default value and a normal select...
As @julien mentions, you can use ref instead of JQuery to get the current value of the select in an uncontrolled component:
class MySelect extends React.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div>
<div>
<button className="current" onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button>
</div>
<select ref="myselect" defaultValue={this.props.defaultValue}>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
</div>
);
}
}
For the other part, defaultValue
should work just as you were trying.
Check this example fiddle: https://jsfiddle.net/y64gbhf8/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With