I am currently working on a React project using Material-UI’s Autocomplete component with React Hook Form to create reusable form elements. I have set up multiple instances of an Autocomplete component configured for multiple selections. Each instance is wrapped in a Controller from React Hook Form. The configuration for each select component looks like this:
'Contact Personal': {
title: 'Contact(s) Personal',
InputFields: [
{
inputType: 'select',
isMultiple: true,
inputTitle: 'Select all Personal contact(s)',
options: personalUsers,
optionLabel: 'fullName',
register: 'personalContact',
},
],
},
'Contact client': {
title: 'Contact(s) client',
InputFields: [
{
inputType: 'select',
isMultiple: true,
inputTitle: 'Select all client contact(s)',
options: customerUsers,
optionLabel: 'name',
register: 'customerContacts',
},
],
},
Each select is meant to function independently within the same form, handling different datasets (trustTeamUsers and customerUsers). However, I’m encountering an issue where if a selection is made in one Autocomplete component, that same selection appears in the other Autocomplete component, despite the different data sources and configuration.
Here’s a simplified version of the component implementation:
import { Controller, useFormContext } from 'react-hook-form';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
export const Select = ({ infos }) => {
const { control } = useFormContext();
return (
<Controller
name={infos.register}
control={control}
render={({ field: { onChange, onBlur, value } }) => (
<Autocomplete
multiple={infos.isMultiple}
options={infos.options}
getOptionLabel={(option) => option[infos.optionLabel]}
value={value || []}
onChange={(_, newValue) => onChange(newValue)}
renderInput={(params) => <TextField {...params} label={infos.inputTitle} />}
onBlur={onBlur}
/>
)}
/>
);
};
I’ve ensured that each instance has a unique register name and tried using unique keys for rendering, but the issue persists. How can I ensure that each select functions independently and does not reuse the values selected from the othe
user22433660 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.