Hey I am stuck with a problem, I using MUI select function for me to select a country. not sure why when I selected the country it change its value but when inside the select box it does not show anything.
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setCountryValue(event.target.value);
};
<FormControl sx={{ m: 1, width: 400 }}>
<InputLabel id="country-label">Country</InputLabel>
<Select
labelId="country-label"
id="country"
value={selectedCountry}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>
{countryList.map((data,index) => (
<MenuItem
key={data.name}
value={data}
>
{data.name}
</MenuItem>
))}
</Select>
<p className="text-black">{selectedCountry.name}</p>
<p className="text-black">{JSON.stringify(selectedCountry, null, 2)}</p>
As you can see, below the blue background color text show the country that I selected, but in the select box is not showing. Not sure where I am doing wrong. Thanks for helping advance.
CodePudding user response:
Your useState
hook has the set function called setSelectedCountry
but on handleChangeCountry
you try to use setCountryValue
which does not update selectedCountry
based on your provided code, please change it like this:
const [selectedCountry, setSelectedCountry] = useState({});
const handleChangeCountry = (event) => {
setSelectedCountry(event.target.value);
};
Also, it seems that selectedCountry
is supposed to be an object? in that case please try passing the Select value as selectedCountry.name
:
<Select
labelId="country-label"
id="country"
value={selectedCountry.name}
onChange={handleChangeCountry}
MenuProps={MenuProps}
>