WUI logo

React Hook Form

Example with React Hook Form form library, yup for validation and Field component to build a simple form.

Usage #

function() {
function FormChildren({ errors, register, control }) {
return (
<>
<Field
error={errors && errors.input_text && errors.input_text.message}
label="Input Text"
maxWidth={300}
>
<InputText {...register('input_text')} />
</Field>
<Field
error={errors && errors.email && errors.email.message}
label="Email"
mt="lg"
maxWidth={300}
>
<InputText {...register('email')} />
</Field>
<Controller
name="submit_checkbox"
control={control}
render={({
field: { onChange, value, ...field },
fieldState: { error }
}) => {
return (
<Field
error={error && error.message}
label="You need to check this checkbox to submit"
mt="xl"
required
>
<Checkbox
{...field}
checked={value}
onClick={onChange}
/>
</Field>
)
}}
/>
<Button mt="lg" type="submit">Submit</Button>
</>
)
}
return (
<HookForm
defaultValues={{
input_text: 'Jungle',
submit_checkbox: false
}}
schemaValidate={() => yup.object().shape({
submit_checkbox: yup.boolean().required().oneOf([true]),
email: yup.string().email().min(6).required()
})
}
>
<FormChildren />
</HookForm>
)
}

Previous

Hint