I would like to make a multiple Select with MUI in my form that is made with Formik, it is my first time using MUI and Formik so I have the question below.
Following the MUI documentation I made the Select like this (I am not sure if the projectSchema and the initialValuesProject are correct.):
/*(...)*/
const projectSchema = yup.object().shape({
usersId: yup.array().of(yup.string()),
});
const initialValuesProject = {
usersId: [],
};
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 250,
},
},
};
const Calendar = () => {
const [personName, setPersonName] = React.useState([]);
const { data } = useGetAllUsersQuery();
const handleChange = (event) => {
const {
target: { value },
} = event;
setPersonName(
// On autofill we get a stringified value.
typeof value === "string" ? value.split(",") : value
);
};
/*(...)*/
return (
/*(...)*/
<Formik
onSubmit={handleFormSubmit}
initialValues={initialValuesProject}
validationSchema={projectSchema}
>
{({ values, handleChange, handleSubmit, setFieldValue }) => (
<form onSubmit={handleSubmit}>
<FormControl size="small" sx={{ m: 1 }}>
<Select
id="encargadoP"
multiple
value={personName}
onChange={handleChange}
MenuProps={MenuProps}
renderValue={(selected) => selected.join(", ")}
sx={{ width: 205 }}
>
{data?.map(({ _id, name }) => (
<MenuItem key={_id} value={name}>
<Checkbox checked={personName.indexOf(name) > -1} />
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
</FormControl>
</form>
)}
</Formik>
);
};
export default Calendar;
This way it works visually but not when Submitting the data.
So I tried to change the value of the Select but that does not show the selected data in the Input, so I would like to know what to put to value and onChange?
I tried this way:
<Select
id="encargadoP"
multiple
value={values.usersId}
onChange={handleChange}
MenuProps={MenuProps}
renderValue={(selected) => selected.join(", ")}
sx={{ width: 205 }}
>
{data?.map(({ _id, name }) => (
<MenuItem key={_id} value={name}>
<Checkbox checked={personName.indexOf(name) > -1} />
<ListItemText primary={name} />
</MenuItem>
))}
</Select>
I am very grateful to those who can help me. <3
2
Answers
Formik uses
name
to recognize your field, so passing attributename="usersId"
inSelect
component may solve the problem.Formik expects a field called
name
that should map to one of th keys in the initialValues object. Ideally, for every key in initialValues object, there should be a field against it with its name attribute.To make the code work, all you got to do is add another attribute in Select Component.