Is there documentation on how I can make these three libraries work together? So far I have found only react-hook-form and react-select together, but not with yup validation. Thank you.
Is there documentation on how I can make these three libraries work together? So far I have found only react-hook-form and react-select together, but not with yup validation. Thank you.
To use react-select with type, install @types/react-select. You can see the Integrating with UI libraries and Schema Validation sections for examples about how to integrate RHF with react-select and yup, click the TS button to see the code examples and the live Codesandboxes in typescript.
Below is the example with react-select and yup to get you started:
interface IFormInputs {
firstName: string;
iceCreamType: { label: string; value: string };
}
const SignupSchema = yup
.object({
firstName: yup.string().required(),
iceCreamType: yup.object().shape({
label: yup.string().required(),
value: yup.string().required()
})
})
.required();
function App() {
const {
register,
handleSubmit,
control,
formState: { errors }
} = useForm<IFormInputs>({
resolver: yupResolver(SignupSchema)
});
const onSubmit = (data: IFormInputs) => {
alert(JSON.stringify(data, null, 4));
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>First Name</label>
<input {...register("firstName")} />
{errors.firstName && <p>{errors.firstName.message}</p>}
</div>
<Controller
name="iceCreamType"
control={control}
render={({ field }) => {
return (
<Select
{...field}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
/>
);
}}
/>
{errors.iceCreamType && <p>{errors.iceCreamType.label?.message}</p>}
<input type="submit" />
</form>
);
}