Bas Slagter
Bas Slagter

Reputation: 9929

How do I have undefined defaultValue with react-hook-form?

I have this form using a Controller from react-hook-form:

<Controller name="myField" control={control} as={(
 <>
   <input type="radio" value="true" />
   <input type="radio" value="false" />
 </>
)}/>

It is complaining: "myField is missing in the 'defaultValue' prop of either its Controller"

But...the thing is. The value needs to be undefined. The user needs to select a value and otherwise it will get a validation error on the form. They need to pick one or the other and we do not want to have a default "yes" or "no" here.

How do I get rid of these warnings? According the docs from react-hook-form I am doing something wrong since it says: "Setting defaultValue inline or at useForm can not be undefined.". But...that's exactly what I want.

Edit: To clearify a bit more. I have a schema validation using yup, like this:

yup.object().shape({
 myField: yup.boolean().required()
});

Now, when I use a defaultValue set to an empty string I need to add a transform: .transform((x) => (x === '' ? undefined : x)) And that's something I would like to avoid because it get's messy real quick.

Upvotes: 1

Views: 10279

Answers (1)

knoefel
knoefel

Reputation: 6949

I would suggest to not use undefined here and instead use null for your defaultValue. null means no value as on the other hand undefined has the meaning that the property/variable has not been defined yet.

If you really need to use undefined for your radio input, you can just use register as your radio input is a native HTML <input /> element.

Edit React Hook Form - Basic (forked)

Upvotes: 2

Related Questions