Reputation: 31
I am using React to create a controlled select element. My app validates the new option value selected by the user and then updates that value on the element. The validation takes some time and the behavior I observe is as follows:
I do not understand why the element reverts to the first index and how can I prevent this (except by setting the value immediately which is undesired in my application)
Use this JSFiddle to see this behavior (select Option2) https://jsfiddle.net/qo39g2j4/
var Select = React.createClass({
render: function() {
return (
<select id="my-select" value={this.props.value} onChange={this.props.onChange}>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
<option value="Option3">Option3</option>
</select>
);
}
});
var Wrapper = React.createClass({
getInitialState: function () {
return {value: "Option3"};
},
onChange: function (event) {
var value = event.target.value;
setTimeout(function () {
this.setState({value: value});
}.bind(this), 1000); // this simulates the validation period
},
render: function () {
return (
<Select
value={this.state.value}
onChange={this.onChange}/>
);
}
});
ReactDOM.render(
<Wrapper/>,
document.getElementById("container")
);
Upvotes: 1
Views: 11312
Reputation: 11
I had the same problem when integrating redux-form within my app, due to an issue in onBlur event handler, so here is how i handled it using customSelect react component :
export default class CustomSelect extends Component {
render() {
const { children, value, onBlur, ...props } = this.props
return (
<select
{...props}
onBlur={() => onBlur(value)}
>
{children}
</select>
)
}
}
Here onBlur eventHandler is explicitly called with the value passed, to keep it selected
Also validation on client-side or server-side should not be represented by a timeout as user is expected to see the wrong input data with the validation message if invalid,
I guess your implementation means that selected option would be visible only if valid which is not the best user experience you can have, if that's the actual case
Solution is based on redux-form react-select bug
Upvotes: 0
Reputation: 1309
Try using defaultValue
instead of value
in your Select
component. Or add event.preventDefault()
in onChange
.
Upvotes: 3