Form Implementation with Validation

Building forms in a React application is streamlined with the use of libraries like react-hook-form and yup for validation. Here’s a guide on creating robust forms using these tools along with predefined components.

Setup with react-hook-form and yup

  • Form Initialization: Initialize your form using useForm from react-hook-form, configuring it with yupResolver from @hookform/resolvers/yup for validation.
const {
  register,
  handleSubmit,
  setValue,
  formState: { errors },
  clearErrors,
} = useForm({
  resolver: yupResolver(yourSchema),
  // other configurations
});
  • Schema Definition: Define your form validation schema using yup. This schema outlines the rules for each form field.
const yourSchema = yup.object().shape({
  // field rules
});
  • Input Fields: Use predefined input components like <OutlinedTextInput /> for a consistent look and feel. Bind them to react-hook-form using register.
<OutlinedTextInput
  label="Your Label"
  inputRef={register("fieldName")}
  validationMessage={errors.fieldName?.message?.toString()}
/>
  • Manual Value Setting: You can manually set form values using setValue. This is particularly useful for handling file uploads or other custom inputs.
setValue("logoUrl", files[0].path);
  • Submit Handler: Use handleSubmit from react-hook-form to handle form submissions. It provides you with form data and error handling.
<form onSubmit={handleSubmit(onSubmit, onError)}>{/* form fields */}</form>
  • Error Display: Utilize validationMessage prop in predefined components to display error messages derived from yup validation.
validationMessage={errors.fieldName?.message?.toString()}
  • Error Clearing: Use clearErrors to manually clear field errors when necessary.
clearErrors("fieldName");
  • File Uploads: For file uploads, components like <FileUpload /> can be integrated with form handling to set form values upon file selection.
<FileUpload
  // props
  onFilesUploaded={(files) => {
    setValue("logoUrl", files[0].path);
    // other actions
  }}
/>
By following these practices and utilizing predefined components, you can create forms that are not only consistent in appearance but also robust in validation and user experience.