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粉4652875922023-09-09 09:17:43
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