How to connect react-hook-form, react-select, and yup in typescript?

Viewed 1232

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.

1 Answers

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.

enter image description here

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>
  );
}

Live Demo

Codesandbox Demo

Related