4

7 Form Components For React Hook Form I Always Use

 2 years ago
source link: https://dev.to/theodorusclarence/7-form-components-for-react-hook-form-i-always-use-1ahd
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Building forms with validation is tedious and repetitive. So my friend and I created a library of form input components so we can just copy the code in every code base, styled minimally with all error validation message using Tailwind CSS and react-icons.


Demo Link

For the demo please visit rhf.clarence.link

Yup Demo

I also made a validation using Yup, you can access it on https://rhf.clarence.link/yup along with the source code.


Setup

1. Install these dependencies

yarn add react-hook-form @tailwindcss/forms react-icons

optional

yarn add react-datepicker react-dropzone react-select
Enter fullscreen modeExit fullscreen mode

2. Configure tailwind.config.js to use @tailwindcss/forms

// tailwind.config.js
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('@tailwindcss/forms'),
    // ...
  ],
}
Enter fullscreen modeExit fullscreen mode

3. Form Structure

This is the default boilerplate, then you can insert the components inside the form

import { FormProvider, useForm } from 'react-hook-form';

export default function Page() {
  const methods = useForm();
  const { handleSubmit } = methods;

  return (
    <>
      <FormProvider {...methods}>
        <form onSubmit={handleSubmit(onSubmit)}>Inputs Here</form>
      </FormProvider>
    </>
  );
}
Enter fullscreen modeExit fullscreen mode

Default Form Components

1. Text Input

Normal Text Input, with error validation

2. PasswordInput

Password input with peek functionality

3. TextArea

Normal TextArea Input

4. DatePicker

Using react-datepicker library, provided with useful props like defaultYear, defaultMonth, locale lang

5. Select (Native)

Select Input using composition

6. File Upload Dropzone

Using react-dropzone library, we can specify selected file extension in the props

7. Select (react-select)

Using react-select library, allowing us to search on the select input


Originally posted on my personal site, find more blog posts and code snippets library I put up for easy access on my site 🚀


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK