Default Value in Select and MenuItem of MUI
Problem Description:
i have a edit form with filled input , the values are shown on textField accordingly but on DropDown it’s not showing default value , [check Select] , [check other Fields]
<Select
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
defaultValue={values.active}
error={touched.active && Boolean(errors.active)}
>
<MenuItem value={true}>Yes</MenuItem>
<MenuItem value={false}>No</MenuItem>
</Select>
i just want to display this default value too , it can be solved if i used option insted of meanuItem but option will not display dropdown items as i want check my code below and image for display dropdown with option
<Select
native
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
defaultValue={values.active}
>
<option value={true} >Yes</option>
<option value={false}>No</option>
</Select>
the code for user binding with values :
const [user, setUser] = useState({});
async function getData(id) {
const fetchedUser = await fetch(`${state.baseUrl}users/${id}`, {
method: "GET",
headers: {
Authorization: `Bearer ${state.loginToken}`,
},
})
.then((response) => response.json())
.catch((err) => console.error(err));
setUser(fetchedUser);}
useEffect(() => {
getData(id);
}, []);
const initialValues = {
fullName: user.fullname,
email: user.email,
userName: user.username,
organ: String(user.organization),
password: "",
role: String(user.role),
active: user.is_active};
Solution – 1
usually
defaultValue
is used for uncontrolled componentyou can have the
boolean
values forMenuItem
here asstring
as all the values inDOM
are strings in general
<Select
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
defaultValue={values.active.toString()} // must match type of value so (convert to string / number)
error={touched.active && Boolean(errors.active)}
>
<MenuItem value={true}>Yes</MenuItem> // value must be string or number
<MenuItem value={false}>No</MenuItem> // value must be string or number
</Select>;
Solution – 2
What is your issue, default value is not getting displayed if you use MenuItem and if you use option then default value is getting display, but the Styling of the Options is old one if I am it’s all about default value then please try the below code
if values object is like
const values = {
active: true,
};
Then the below code will be
<Box>
<Select
name="active"
labelId="active-label"
id="active"
onChange={handleChange}
onBlur={handleBlur}
value={values.active}
sx={{ width: "10rem" }}
>
<MenuItem value={true}>Yes</MenuItem>
<MenuItem value={false}>No</MenuItem>
</Select>
</Box>