Create a simple form in React using react-hook-form

Today, we’ll show you how to create a simple form in React using react-hook-form package. In the previous article, we have explained how to create a form without any package in React.

In this form example, we will use a very popular library to build a form and in the upcoming examples, we’ll show you how to validate it.

Demo Application

Output - Create a simple form in React using react-hook-form - Clue Mediator
Output – Create a simple form in React using react-hook-form – Clue Mediator

Create a simple form in React using react-hook-form

  1. Project structure
  2. Package dependencies
  3. Design a simple form
  4. Integrate the react-hook-form
  5. Output

1. Project structure

Refer to the following React project structure for the form example.

  • form-using-react-hook-form
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

In this example, we have to install the react-hook-form npm package. Run the following command to install the react-hook-form.

You will find the version of following packages in React application.

react
^18.2.0
react-hook-form
^7.41.3

3. Design a simple form

To start with, we will create a simple form design and store the data on click of the submit button.

App.js

Here, we have added three different fields named name, email, and website. At the end of the form we are displaying the form values on the page.

4. Integrate the react-hook-form

Now, let’s integrate the react-hook-form in the above form. We have to add the following code in the existing form.

In the above code, we have used the register() method to register the fields and used the handleSubmit() method to get the submitted data on submit. Both the methods, we have exported from the useForm().

5. Output

Let’s put all the code together and see how it looks.

App.js

Run the application and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *