ReactJS: select default from props without onChange event?
So I'm just wondering if I need to have an onChange event handler for the selected component in React?
I have a propeller passing the default value for the option I want to select. It's not a problem if I have:
<select
value={this.props.defaultValue}
>
<option value="a">A</option>
<option value="b">B</option>
</select>
Also, 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.
How do I get the value using Jquery, I don't need state or any kind of transfer between child and parent ...
Is there an easy way to allow the select to receive the default from the props and still work like a normal selection, where changing the parameter changes the value that I can grab with jquery, or should I have a state and an onChange handler?
Thank!
What I've 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 and a normal selection ...
source to share
As @julien mentions, you can use ref instead of JQuery to get the current value of the select in an unchecked 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>
);
}
}
On the other hand, defaultValue
should work the same way as you tried.
Check out this example fiddle: https://jsfiddle.net/y64gbhf8/1/
source to share
you can try Uncontrolled components
you don't need to write an event handler to update the state, the DOM will handle it, then you can use ref to get form values ββfrom the DOM
source to share