Store Button Group Value in react-hook-form State

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?

To successfully update and retrieve the selectedOption value when a button is clicked in the Button Group, you need to make a small modification to your code.

Instead of using the setValue function from react-hook-form, you can directly update the value of field.value in the onClick event handler.

Here’s the modified code:

import { ButtonGroup, Button } from '@mui/material';
import { useForm, Controller } from 'react-hook-form';

export default function MyComponent() {
  const { control, getValues } = useForm();

  const options = ['Option1', 'Option2', 'Option3'];

  return (
    <Controller
      name="selectedOption"
      control={control}
      render={({ field }) => (
        <ButtonGroup>
          {options.map((option) => (
            <Button
              key={option}
              variant={field.value === option ? 'contained' : 'outlined'}
              onClick={() => {
                field.onChange(option);
              }}
            >
              {option}
            </Button>
          ))}
        </ButtonGroup>
      )}
    />
  );
}

With this modification, the selectedOption value will be updated correctly when a button is clicked in the Button Group.