CodexBloom - Programming Q&A Platform

React Hook Form with Material-UI Autocomplete - implementing Value Updates and Errors

👀 Views: 206 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-15
react react-hook-form material-ui autocomplete validation JavaScript

I'm integrating two systems and I've been struggling with this for a few days now and could really use some help... I'm working on a form using React Hook Form (v7) and Material-UI (v5) where I have an Autocomplete component for selecting multiple options. The selected values are not updating correctly in the form's state, and I'm also working with issues with validation. Despite using `Controller`, my validation rules are not triggering, and the `onChange` function does not seem to register the selected values properly. I've set up my form like this: ```javascript import React from 'react'; import { useForm, Controller } from 'react-hook-form'; import Autocomplete from '@mui/material/Autocomplete'; import TextField from '@mui/material/TextField'; const MyForm = () => { const { control, handleSubmit, formState: { errors } } = useForm({ defaultValues: { options: [] }, }); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <Controller name="options" control={control} rules={{ required: 'At least one option is required' }} render={({ field }) => ( <Autocomplete {...field} multiple options={['Option 1', 'Option 2', 'Option 3']} getOptionLabel={(option) => option} onChange={(event, value) => field.onChange(value)} renderInput={(params) => <TextField {...params} label="Select Options" behavior={!!errors.options} helperText={errors.options ? errors.options.message : ''} />} /> )} /> <button type="submit">Submit</button> </form> ); }; export default MyForm; ``` The behavior message I see when submitting is 'At least one option is required', but even when I select options, the validation still fails. Additionally, the selected values do not seem to continue after submission. I've tried logging the values in different parts of the code to debug, but they seem to only log the previous state. I'm using the latest versions of both libraries. Any help to get the values updating correctly and the validation working would be greatly appreciated! Any ideas what could be causing this?