When using a controlled HTML <select> tag in React.
About the snippet below:
Why this works:
OPTION #1
function changeSelect(event) {
const newValue = event.target.value;
setNestedState((prevState) => {
return({
...prevState,
propA: newValue
});
});
}
And this doesn't? (it works only on the first change)
OPTION #2
function changeSelect(event) {
setNestedState((prevState) => {
return({
...prevState,
propA: event.target.value
});
});
}
SNIPPET (using option #2)
function App() {
const [nestedState,setNestedState] = React.useState({
propA: 'foo1',
propB: 'bar'
});
function changeSelect(event) {
// const newValue = event.target.value;
setNestedState((prevState) => {
return({
...prevState,
propA: event.target.value // THIS DOES NOT WORK
});
});
}
return(
<React.Fragment>
<div>My nested state:</div>
<div>{JSON.stringify(nestedState)}</div>
<select
value={nestedState.propA}
onChange={changeSelect}
>
<option value='foo1'>foo1</option>
<option value='foo2'>foo2</option>
<option value='foo3'>foo3</option>
</select>
</React.Fragment>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>