Mir Stephen
Mir Stephen

Reputation: 1927

Storing Selected Value from Button Group in react-hook-form State

I'm attempting to save the selected value from MUI Button Group to the react-hook-form's state, but facing some issues - the value is not being updated correctly.

codesandbox link here

Here's a generic version of my code:

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 used setValue('selectedOption', option) and not sure if it is a nice practice though.

The issue I'm facing is that when I click on a button in the Button Group, I expect the selectedOption value in the form state to be updated to the value of the clicked button. However, the getValues method doesn't seem to reflect the updated state.

What could be the issue here? How can I successfully update and retrieve the selectedOption value when a button is clicked in the Button Group?

Thanks in advance for your help!

Upvotes: 2

Views: 329

Answers (1)

Steve G
Steve G

Reputation: 13367

You're going to want to use the FormProvider with useFormContext if you don't want to pass context as a prop to your Form component. (Which is what I assume you want to do by looking at your example).

From the useFormContext docs:

useFormContext: Function

This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop.

For example:

export default function MyComponent() {
  const methods = useForm();

  return (
    {/* Add FormProvider with useForm return props */}
    <FormProvider {...methods}>

      ...

    </FormProvider>
  );
}

const Form = () => {
  // Retrieve your setter/getter functions from useFormContext
  const { control, setValue, getValues } = useFormContext();
  const options = ["Option1", "Option2", "Option3"];

  ...
};

Working CodeSandbox: https://codesandbox.io/s/react-hook-form-no-props-kngps3?file=/src/Form.jsx

Upvotes: 1

Related Questions