'Material-UI Select shows the wrong value: More explanation in the post
I have these choices where user can choose Cup, Mug, and Case. The problem here is that if I'll choose Cup, the value shows "Mug". And if I'll choose "Mug", it will display "Case". What is wrong with the codes here?
import React, { useState } from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
export default function BasicSelect() {
const [prod, setProd] = useState("");
const [qty, setQty] = useState(0);
const [color, setColor] = useState("");
const [age, setAge] = useState("");
const handleChange = (event) => {
setProd(event.target.value);
console.log(prod);
};
return (
<Box sx={{ minWidth: 120 }}>
<FormControl fullWidth>
<InputLabel id="demo-simple-select-label">Age</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={prod}
label="Age"
onChange={handleChange}
>
<MenuItem value="Cup">Cup</MenuItem>
<MenuItem value="Mug">Mug</MenuItem>
<MenuItem value="Case">Case</MenuItem>
</Select>
</FormControl>
</Box>
);
}
codesandbox link: https://codesandbox.io/s/basicselect-material-demo-forked-4g34r?file=/demo.js:0-1094
Solution 1:[1]
If you take a look at your hanldeChange
const handleChange = (event) => {
setProd(event.target.value);
console.log(prod);
};
In consol.log(prod) prod is the variable what event.target.value will be. What you are actually seeing in the output console is the previous state, because setProd hasn't re-rendered the UI in time for the prod to hold the event.target.value that you have selected in the UI.
If you want to see in the output console what value you have selected in the dropdown use console.log like this console.log(event.target.value)
You can take a look here for more information on the lifecycle of setState https://reactjs.org/docs/state-and-lifecycle.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dparr |
