I’m trying to change the state of a component but it keep rendering the previous state.
From what I understood, the component is rendered before the state is getting saved and I need to use a callback function, except that I did not succeed.
Here is a simplified code of what I’m trying to do:
export default function ColorPick() {
const [color, setColor] = useState('');
const [choice, setChoice] = useState('blue');
const handleColor = (event, newChoice) => {
setChoice(newChoice)
if(choice === 'blue'){
setColor('blue')
}else{
setColor('red')
}
};
return (
<select onChange={handleColor} value={choice}>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<h1>{color}</h1>
);
}
Thank you
>Solution :
You can just use the event parameter which returns the selected value. Then your handleColor will look like this
const handleColor = (event) => {
console.log(event.target.value);
if (event.target.value === "blue") {
setColor("blue");
} else {
setColor("red");
}
};
<select onChange={handleColor}>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
<h1>{color}</h1>
Then also you don’t need to use the choice state
Codesandbox example