Reputation: 1558
OS: Windows 10 Pro Browser: Opera
So, the issue I'm having, is that when a selection with onChange() is made, the selected option will immediately display (go back) to its previous selected option state.
So, and using the following code:
cont options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
class funcName extends React.Component {
render() {
return (
logChange = (val) => {
console.log("Selected: " + val);
}
<Select
name="form-field-name"
value="one"
options={options}
onChange={logChange}
/>
);
}
}
attempting to select option 'Two' is never retained. Immediately the selection is made it goes back to select option 'One' and the displayed value of (val) is always 'One'. If I comment out the onChange line, then the select box functions as expected.
What is the issue here?
Upvotes: 0
Views: 248
Reputation: 611
Your root problem is that you don't actually have a component doing anything in your code, so the Select just renders with the static props you set in the beginning.
As Alex says, you need to update the value
prop that you are sending to the Select component in order for it to update visually. At a very basic level you do this by calling setState on a parent component, which you have not created in your example, and pass that value to the child Select component.
<Select
name="form-field-name"
value={this.state.selection.value}
options={options}
onChange={this.changeSelection}
/>
I have updated your code here for a complete working sample: https://plnkr.co/edit/TlUe2eJd3OSxGkdHIKJP?p=preview
Upvotes: 1
Reputation: 2366
By specifying the value
field you reassign the value each time the render function is invoked. Use defaultValue
instead.
LE: Might be worth reading a bit about controlled vs uncontrolled components: https://facebook.github.io/react/docs/forms.html
Upvotes: 1