Created
January 4, 2023 18:58
-
-
Save Wellers0n/d5dffb1263ae0fed5046e45c47a7c4a7 to your computer and use it in GitHub Desktop.
MuiltSelect with mui
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { TextField } from '@mui/material'; | |
import Autocomplete from '@mui/material/Autocomplete'; | |
import { useFormikContext } from 'formik'; | |
import React from 'react'; | |
type OptionsValues = { | |
title: string, | |
value: string | |
} | |
type Props = { | |
id: string, | |
name: string, | |
label: string, | |
options: OptionsValues[] | |
} | |
function MuiltSelect(props: Props) { | |
const { options, name, label, id } = props | |
const formik = useFormikContext(); | |
return ( | |
<Autocomplete | |
{...props} | |
multiple | |
options={options} | |
getOptionLabel={(option: any) => option.title} | |
onChange={(_, value) => formik.setFieldValue(name, value)} | |
filterSelectedOptions | |
isOptionEqualToValue={(item: any, current: any) => item.value === current.value} | |
renderInput={(params) => ( | |
<TextField | |
{...params} | |
id={id} | |
name={name} | |
label={label} | |
variant={"outlined"} | |
onChange={formik.handleChange} | |
error={formik.touched[name] && Boolean(formik.errors[name])} | |
helperText={formik.errors[name]} | |
value={formik.values[name]} | |
fullWidth | |
/> | |
) | |
} | |
/> | |
) | |
} | |
export default MuiltSelect | |
in this case we use the formik context to update the state
<MuiltSelect
id="my-autocomplete"
name="myAutocomplete"
label="My Autocomplete"
onChange{formik.handleChange}
value={values.myAutocomplete}
error={Boolean(touched.myAutocomplete && errors.myAutocomplete)}
helperText={touched.myAutocomplete && errors.myAutocomplete}
helperText={formik.errors['myAutocomplete']}
error={true}
/>`
like this?
`
this doesn't work because the autocomplete set value is different from other inputs, you need to pass FormikProvider
around your form and this code will works
thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi how to use this component ? how to pass props to componet? i want pass onChange to component