Store selected value in button group in react-hook-form state
P粉106715703
P粉106715703 2023-09-08 18:17:15
0
1
492

I'm trying to save the selected value in a MUI button group to the state of a react-hook-form, but I'm having some problems - the value is not updating correctly.

codesandbox link here

This is 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) but not sure if this is a good practice.

The problem I'm facing is that when I click a button in the button group, I want the selectedOption value in the form state to be updated with the value of the clicked button. However, the getValues ​​method doesn't seem to reflect the updated state.

What could go wrong here? How can I successfully update and retrieve the selectedOption value when a button in a button group is clicked?

Thanks in advance for your help!

P粉106715703
P粉106715703

reply all(1)
P粉465287592

You will need to use FormProvider a> with useFormContext If you don't want to The context is passed as a prop to your Form component. (I think you want to do this by looking at examples).

From useFormContext Documentation:

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!