Skip to content

Instantly share code, notes, and snippets.

@Wellers0n
Created January 4, 2023 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wellers0n/d5dffb1263ae0fed5046e45c47a7c4a7 to your computer and use it in GitHub Desktop.
Save Wellers0n/d5dffb1263ae0fed5046e45c47a7c4a7 to your computer and use it in GitHub Desktop.
MuiltSelect with mui
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
@mm0hammadi
Copy link

hi how to use this component ? how to pass props to componet? i want pass onChange to component

@Wellers0n
Copy link
Author

in this case we use the formik context to update the state

@mm0hammadi
Copy link

mm0hammadi commented Aug 7, 2023

<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?
`

@Wellers0n
Copy link
Author

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

@mm0hammadi
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment