Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook Form Dynamic Require

Good Day All,

Im using react hook form and I want set required dynamically on one text-input. I have a useState that tracks the delivery method and radio buttons that update that state. And then the text-input required should be based dynamically on that state. So if the delivery method is "Delivery" we require your address if its "Pickup" we dont require your address. I hope that makes sense.

In the code below the show/hide functionality works as expected however the dynamic require does not.

const [ delivery, setDelivery ] = useState(false);

<InfoBlock>
  <strong>Delivery Method</strong>
  <RadioGroup>
    <RadioBlock>
      <input type="radio" id="pickup" name="pickup" {...register("deliveryMethod", {required: true})} 
        value="pickup" onClick={() => setDelivery(false)} />
      <h5>Pickup</h5>
    </RadioBlock>                
    <RadioBlock>
      <input type="radio" id="deliver" name="delivery" {...register("deliveryMethod", {required: true})}  
        value="delivery" onClick={() => setDelivery(true)} />
      <h5>Delivery</h5>
    </RadioBlock>                   
  </RadioGroup>
</InfoBlock>
<ErrorMsg>
  {errors.deliveryMethod && errors.deliveryMethod.type === 'required' && "Please select delivery method"}
</ErrorMsg>

{delivery ? 
  <div>
    <InfoBlock>
      <strong>Address</strong>
      **<input type="text" id="address" name="address" 
        {...register("address", {required: delivery })}  />**
    </InfoBlock>
    <ErrorMsg>
      {errors.address && errors.address.type === 'required' && "Address is required"}
    </ErrorMsg>            
  </div> : null} 
like image 412
Lyle Phillips Avatar asked Oct 19 '25 23:10

Lyle Phillips


1 Answers

  1. You don't need useState here, as you can use RHF for handling the state of your radio input value - you can just use watch, provided by useForm, to watch for changes of that field
  2. As you conditionally render the 'address' input only for a certain delivery method, you can also just set required to true for the rules of that field

There is one important thing: since v7 there is no automatically removal of fields which will unmount (in your case, due to conditional rendering). So for now, you have to unregister the field manually. This is why in the CodeSandbox there is the unregister call, when clicking the 'pickup' radio option.

However, there is currently a discussion ongoing, as this new behaviour brings disadvantages in some cases (such as conditional rendering of fields). So maybe it will be possible again in the future to unregister fields automatically on unmount.

Edit React Hook Form - Basic (forked)

like image 189
knoefel Avatar answered Oct 21 '25 22:10

knoefel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!