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}