reactjsreact-hook-form

How to use react hook form's Controller with radio buttons


The Problem:

What I'm trying to do:

Examples:

Code Sandbox

  1. Use WrapperRadio in RegistrationForm
    <form onSubmit={onSubmit}>
      <WrapperRadio
        control={control}
        name="radioSelection"
        label="This is a label"
      />
    ...
    </form>
  1. Using Controller in WrapperRadio

    return (
        <div>
          <Controller
            control={control}
            name={name}
            render={({ field }) => <RadioButton {...field} label={label} />}
          />
        </div>
      );
  1. Atomic RadioButton component
    return (
        <fieldset className="max-w-sm">
          <input
            ref={ref}
            id={name}
            name={name}
            type="radio"
            aria-label={label}
            {...props}
          />
          <label htmlFor={name} className="block text-sm font-medium text-gray-700">
            {label}
          </label>
        </fieldset>
      );

Solution

    1. Use WrapperRadio in RegistrationForm - you should pass in a default value.

         <form onSubmit={onSubmit}>
            <WrapperRadio
              control={control}
              name="radioSelection"
              label="This is a label"
              value={true}
            />
          </form>
      
    2. Using Controller in WrapperRadio

              return (
                <div>
                   <Controller
                    control={control}
                    name={name}
                    render={({ field: {onChange, ...props} }) => 
                    <RadioButton
                    onChange={e => onChange(e.target.checked)}
                    {...props} label={label} />}
                 />
                </div>