Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shadcn RadioButton not checked despite changed value from React-hook-form

I have the following controlled RadioGroup/RadioItem components from Shadcn:

<form onSubmit={handleSubmit(saveAnswer)}>
  <p className="my-4 text-lg">{props.question}</p>
  <Controller
    control={control}
    name="answer"
    render={({ field }) => {
      return (
        <RadioGroup
          value={chosenAnswers[props.questionIndex]}
          onValueChange={field.onChange}
        >
          {choiceElements}
        </RadioGroup>
      )
    }}
  />
  <Button type="submit">save answer</Button>
  <DevTool control={control} />
</form>

choiceElements:

const choiceElements = props.choices.map(answerText => {
  return (
    <div key={answerText}>
      <RadioGroupItem
        value={answerText}
        id={answerText}
      />
      <Label htmlFor={answerText}>{answerText}</Label>
    </div>
  )
})

I am also saving each choice in {index: answer} format in global Zustand state (from SaveAnswer). The global state variable is chosenAnswers.

The problem occurs after I initially select and save (using a submit button) a choice: When I select another one, the visual indicator stays on the saved, initial choice, even though react-hook-form devtools tell me that value has changed appropriately to a new value.

enter image description here

In this image, I have initially selected the first answer (the one highlighted with a black dot). After clicking the second option, the "answer" value changes accordingly to "The spread of religious tolerance across Europe". However, UI is not updated, namely the black dot is not on the second choice. The black dot only appears when I hit "save answer" again. I want it to reflect changing state even without saving it.

like image 775
semi_92 Avatar asked Sep 20 '25 12:09

semi_92


1 Answers

I just stumbled upon the same issue. The only thing that worked for me is recognizing that RadioGroupItem honors checked attribute and use that instead.

<RadioGroup
  defaultValue={field.value}
  onValueChange={field.onChange}
>
  <FormItem >
    <FormControl>
      <RadioGroupItem
        value="0"
        checked={field.value === "0"}
      />
    </FormControl>
    <FormLabel>
      Option 0
    </FormLabel>
  </FormItem>
  <FormItem >
    <FormControl>
      <RadioGroupItem
        value="1"
        checked={field.value === "1"}
      />
    </FormControl>
    <FormLabel>
      Option 1
    </FormLabel>
  </FormItem>
  <FormItem >
    <FormControl>
      <RadioGroupItem
        value="2"
        checked={field.value === "2"}
      />
    </FormControl>
    <FormLabel>
      Option 2
    </FormLabel>
  </FormItem>
</RadioGroup>

Perhaps, that may work for you too. Your choiceElements just have to know about field.value.

like image 103
aldnav Avatar answered Sep 22 '25 03:09

aldnav