Skip to main content

Command Palette

Search for a command to run...

A Simple Guide to Build React Form with Hooks

Updated
A Simple Guide to Build React Form with Hooks
V

I'm a solutions engineer lead, GitHub Star, Director of WomenDevsSG, and co founder of ragTech. I work at the intersection of tech, systems, and leadership, and this blog is where I share my journey through all three. Expect honest reflections, real experiences, and thoughts that are still forming rather than polished career advice.

With React, there are many ways that you can build forms. The simplest way that I found is by React Hook Forms. In this article, I'll show you how to create and build a React form easily with React Hook Forms.

Step 1: Build the Form

React Hook Forms provides a tool for you to easily create your forms. Then you can copy the code snippet generated for your form and paste it to your project. Head to the Builder to build your own form.

Builder.PNG

Add Optional Details

In the Builder, you can also customize the input attributes such as if it is required or its max length. Again, the code will be automatically generated so it's very convenient.

input.PNG

Once you have built your form, you can click 'Generate Form' to see what it looks like. Here's my example:

example.PNG

Step 2: Paste the Code

First, run npm install react-hook-form in your project.

Now that you've generated your form, simply paste it to your project file. For my example, I'll paste it into App.js.

import React from 'react';
import { useForm } from 'react-hook-form';

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => console.log(data);
  console.log(errors);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input type="text" placeholder="First name" name="First name" ref={register({required: true, maxLength: 80})} />
      <input type="text" placeholder="Last name" name="Last name" ref={register({required: true, maxLength: 100})} />
      <input type="text" placeholder="Email" name="Email" ref={register({required: true, pattern: /^\S+@\S+$/i})} />
      <input type="tel" placeholder="Mobile number" name="Mobile number" ref={register({required: true, minLength: 6, maxLength: 12})} />

      <input name="Gender" type="radio" value="Female" ref={register({ required: true })}/>
      <input name="Gender" type="radio" value="Male" ref={register({ required: true })}/>

      <input type="submit" />
    </form>
  );
}

Step 3: Submit Form

The form is now in our app. All we need to do is to take care of what happens when a user submits the form. To do this, we need to add some code to the onSubmit function.

Currently, the onSubmit code generated for us only returns console.log(data) where data contains the user's submitted form data in JSON format like:

// sample data object
{
  "First name": "Victoria",
  "Last name": "Lo",
  "Email": "victoria@example.com",
  "Mobile number": "9999999999",
  "Gender": "Female"
}

Let's say we want to take this data and POST it to our database.

Our onSubmit function will be as follows:

const onSubmit = data =>{
      //create requestOptions to prepare for post
      const requestOptions = {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data), //send the form data
      };

      //post form data to database or something
      fetch(someURL, requestOptions)
      .then(doSomething); 
}

And done!

And that's how you can create a form easily with React! It's good to use the Builder tool to create forms fast but I do encourage you to read the documentation more in detail to understand how it works and include more advanced options on your own. Thanks for reading this quick tutorial. I hope you find it helpful! Please feel free to ask any questions in the comments below. Cheers!

S
Skay5y ago

Great Post once again!! Quick q - If I have integrate CSS libraries like Bootstrap. Is that supported? Currently, for the application I'm building, I'm using React Bootstrap for CSS.

Definitely using React Forms seem to be the way forward, provided it has ways to allow for other integrations.

1
V

Hi thanks for reading! As for your question, I have tried using React Bootstrap and unfortunately it doesn't seem to work at the moment.

However, you can use Bootstrap so for e.g. instead of React Bootstrap <Col/> and <Row/>, you can use <div className="col"> and <div className="row>.

Hope that helps!

1
S
Skay5y ago

Victoria Lo Thanks for replying! Got it.. lemme try it out..

1
C

Recently started using React-hook-form, really great lib. Thanks for sharing!

1
V

No problem! Yes, it's great isn't it?

1
C

Yeah, it really is, solved a bit complex problem in a very simple way!

A

This is beautiful Victoria. Thanks for sharing with us.

1
V

No problem! Thanks for reading :)

N

this was pretty easy to follow.

1
V

Yayy hope it's helpful :)

R

Thanks, needed this.

1
V

Glad it's useful :)

Super Newbie Web Dev

Part 23 of 49

Let's be honest. We all started from level 0. There's no shame in that. Here's the series for the newbies~ Hope you can learn and feel free to ask a lot of questions! Check my other series: Random project to build

Up next

Why React Keys Matter: An Introduction

When working with any type of list in React, you will often encounter this warning if you forgot to include a key prop: Warning: Each child in a list should have a unique “key” prop So, why does React tell you to include keys and why is it important...