I’m attempting to save the value from a Material UI Button Group to the react-hook-form’s state, but the value is not being updated correctly.
Below is a generic version of my code with a codesandbox link for reference:
import { ButtonGroup, Button } from '@mui/material'
import { useForm, Controller } from 'react-hook-form'
export default function MyComponent() {
const { control, setValue, getValues } = useForm()
const options = ['Option1', 'Option2', 'Option3']
return (
<Controller
name="selectedOption"
control={control}
render={({ field }) => (
<ButtonGroup>
{options.map((option) => {
return (
<Button
key={option}
variant={field.value === option ? 'contained' : 'outlined'}
onClick={() => {
setValue('selectedOption', option) {/* this trick didn't work */}
}}
>
{option}
</Button>
)
})}
</ButtonGroup>
)}
/>
)
}
I’m using setValue('selectedOption', option)
to update the state, but it doesn’t seem to work. How can I successfully update and retrieve the selectedOption
value when a button is clicked in the Button Group?