Reactjs: Select With Default Value From Props Without Onchange Event?
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 sele
Solution 1:
As @julien mentions, you can use ref instead of JQuery to get the current value of the select in an uncontrolled component:
classMySelectextendsReact.Component {
constructor(props) {
super(props);
this.state = { currentValue: this.props.defaultValue };
}
updateValue() {
this.setState({ currentValue: this.refs.myselect.value });
}
render () {
return (
<div><div><buttonclassName="current"onClick={this.updateValue.bind(this)}>{this.state.currentValue}</button></div><selectref="myselect"defaultValue={this.props.defaultValue}><optionvalue="a">A</option><optionvalue="b">B</option><optionvalue="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/
Solution 2:
you can try Uncontrolled Components
you don't need to write event handler for state update,DOM will handle it, then you can use a ref to get form values from the DOM
Post a Comment for "Reactjs: Select With Default Value From Props Without Onchange Event?"