avatarChad Murobayashi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3299

Abstract

g">"password"</span> placeholder<span class="hljs-operator">=</span><span class="hljs-string">"Password"</span> name<span class="hljs-operator">=</span><span class="hljs-string">"password"</span> /> <input type<span class="hljs-operator">=</span><span class="hljs-string">"submit"</span> /> </form> )<span class="hljs-comment">;</span> }<span class="hljs-comment">;</span></pre></div><p id="224a">I added a few basic stylings too, just to make it look a little nicer. Now if we open up our application it will look something like this.</p><figure id="505c"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*zfe5W1VS8wyR56xR7YSB-g.png"><figcaption></figcaption></figure><h1 id="7dcc">Using React Hook Form</h1><p id="7abc">To use the React Hook Form library, let’s first install it into our project. You can find the npm package <a href="https://www.npmjs.com/package/react-hook-form">here</a>.</p><p id="f7cf">We will import the <code>useForm</code> hook from the library.</p><div id="69a6"><pre><span class="hljs-keyword">import</span> { useForm } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-hook-form'</span>;</pre></div><p id="5d48">Then, call it inside of a function component. This hook will give us three variables when we call it, <code>register</code> <code>handleSubmit</code> and <code>errors</code>.</p><div id="ce77"><pre><span class="hljs-type">const</span> { <span class="hljs-keyword">register</span>, handleSubmit, errors } = <span class="hljs-built_in">useForm</span>();</pre></div><p id="5358">To track the changes to our inputs, we will pass <code>register</code> as a ref to each input that we want to track. Now each input will look like this.</p><div id="7902"><pre><input type<span class="hljs-operator">=</span><span class="hljs-string">"text"</span> placeholder<span class="hljs-operator">=</span><span class="hljs-string">"Username"</span> name<span class="hljs-operator">=</span><span class="hljs-string">"username"</span> ref<span class="hljs-operator">=</span>{register} /></pre></div><p id="b184">Next, let’s take care of the handle submit functionality of the form. We will create a <code>onSubmit</code> function, which will accept data. For now, we will just output it to the console.</p><div id="c820"><pre>const onSubmit <span class="hljs-operator">=</span> (data) <span class="hljs-operator">=</span>> { console.log(data)<span class="hljs-comment">;</span> }<span class="hljs-comment">;</span></pre></div><p id="cee0">On the form, add the <code>handleSubmit</code> function as a prop and pass <code>onSubmit</code> as a callback function.</p><div id="a7ef"><pre><form className<span class="hljs-operator">=</span><span class="hljs-string">"App"</span> onSubmit<span class="hljs-operator">=</span>{handleSubmit(onSubmit)}></pre></div><p id="166f">Now, when we add data to the form and submit it, we will see the output in our console. We now have a nice object with all of our form data.</p><figure id="200a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*I4mu3webRxQmxEAaqkbNDg.png"><figcaption></figcaption></figure><p id="8d2b">Don’t forget to add a name prop to the inputs. The name we pass to the inputs will be used as the key in our data obje

Options

ct.</p><h1 id="7ede">Adding Validation</h1><p id="4658">To add validation rules to the form, we can pass an optional object as an argument to <code>register</code>.</p><p id="73d8">For example, if we want to make an input required, we can simply add the following to any input.</p><div id="f043"><pre><<span class="hljs-keyword">input</span> <span class="hljs-keyword">type</span>="text" placeholder="Username" <span class="hljs-type">name</span>="username" <span class="hljs-keyword">ref</span>={register({ required: <span class="hljs-keyword">true</span> })} /></pre></div><p id="cd6e">Now, if we try to submit the form without a username, it will not work.</p><p id="4cf1">We can display an error message by using the <code>errors</code> value from before. Any errors that occur will become a prop on the errors object and we can use this to display errors.</p><p id="c0fc">For example, if a user does not write in a username (which we made required), we can display an error like so.</p><div id="683d"><pre>{errors.username && <span class="hljs-tag"><<span class="hljs-name">p</span>></span>Username required<span class="hljs-tag"></<span class="hljs-name">p</span>></span>}</pre></div><figure id="2a80"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*8L8_wS5sxkXuOCuzC1aTSw.png"><figcaption></figcaption></figure><p id="1e87">The list of supported validation rules are:</p><ul><li>required</li><li>min</li><li>max</li><li>minLength</li><li>maxLength</li><li>pattern</li><li>validate</li></ul><p id="a4e5">If you were following along with the code, we should now have a form with the validation set up like below.</p> <figure id="1a6b"> <div> <div>

            <iframe class="gist-iframe" src="/gist/chadmuro/06b0a86fff9e92447be7e6b11a552f71.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h1 id="5abc">Wrapping Up</h1><p id="914c">Thanks for reading! I hope this article was helpful for you to get started working with the React Hook Form library.</p><p id="26ee">It is easy to use, good for performance, and requires a lot less code. Give it a shot in your next application where a form is needed.</p><p id="1829">If you want to check out the full source code for the example we created, check out the GitHub repository <a href="https://github.com/chadmuro/medium-react-hook-form">here</a>.</p><p id="1a1e">To learn about another useful React library, check out the article below where we look at the React Icons library.</p><div id="1443" class="link-block">
      <a href="https://javascript.plainenglish.io/tutorial-and-beginners-guide-to-using-react-icons-77c614696301">
        <div>
          <div>
            <h2>A Beginner’s Guide To Using React Icons</h2>
            <div><h3>Get all the icons you need in one place</h3></div>
            <div><p>javascript.plainenglish.io</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*logBdQ4WYF3HuA2s)"></div>
          </div>
        </div>
      </a>
    </div></article></body>

The Easiest Way to Deal with Forms in React

Use React Hook Form to improve performance in your application

Photo by Leon Dewiwje on Unsplash

Forms are an essential part of any website or application. You will see them used everywhere from login/signup screens to adding and updating data.

When using React, typically we would want to create a controlled component when dealing with inputs.

For example, we will need to create a state variable and set this as the value of the input. Then we will need to add an onChange event listener to the input. Now, whenever the input is updated, we have a controlled state within our application.

As you can see from above, there is a few extra lines of code needed to pull this off. Imagine if we have a form with multiple inputs? We will need to create a separate state for each input and add the value and onChange listener for each one. Also, every time we change the value of the input, it will cause a rerender of the component.

To make things a lot simpler, welcome the React Hook Form library. It is described as,

“Performant, flexible and extensible forms with easy-to-use validation.”

Sounds good, doesn’t it? In this article, we will take a look at the React Hook Form library. We will start off with learning how to implement it in our app, then take a look at how to handle validation.

Getting Started

To show off this library, we will build a simple form. First off, let’s create a form in our React project like below. It is a simple form with three input fields and a submit button.

const App = () => {
  return (
    <form className="App">
      <input type="text" placeholder="Username" name="username" />
      <input type="email" placeholder="Email" name="email" />
      <input type="password" placeholder="Password" name="password" />
      <input type="submit" />
    </form>
  );
};

I added a few basic stylings too, just to make it look a little nicer. Now if we open up our application it will look something like this.

Using React Hook Form

To use the React Hook Form library, let’s first install it into our project. You can find the npm package here.

We will import the useForm hook from the library.

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

Then, call it inside of a function component. This hook will give us three variables when we call it, register handleSubmit and errors.

const { register, handleSubmit, errors } = useForm();

To track the changes to our inputs, we will pass register as a ref to each input that we want to track. Now each input will look like this.

<input
  type="text"
  placeholder="Username"
  name="username"
  ref={register}
/>

Next, let’s take care of the handle submit functionality of the form. We will create a onSubmit function, which will accept data. For now, we will just output it to the console.

const onSubmit = (data) => {
  console.log(data);
};

On the form, add the handleSubmit function as a prop and pass onSubmit as a callback function.

<form className="App" onSubmit={handleSubmit(onSubmit)}>

Now, when we add data to the form and submit it, we will see the output in our console. We now have a nice object with all of our form data.

Don’t forget to add a name prop to the inputs. The name we pass to the inputs will be used as the key in our data object.

Adding Validation

To add validation rules to the form, we can pass an optional object as an argument to register.

For example, if we want to make an input required, we can simply add the following to any input.

<input
  type="text"
  placeholder="Username"
  name="username"
  ref={register({ required: true })}
/>

Now, if we try to submit the form without a username, it will not work.

We can display an error message by using the errors value from before. Any errors that occur will become a prop on the errors object and we can use this to display errors.

For example, if a user does not write in a username (which we made required), we can display an error like so.

{errors.username && <p>Username required</p>}

The list of supported validation rules are:

  • required
  • min
  • max
  • minLength
  • maxLength
  • pattern
  • validate

If you were following along with the code, we should now have a form with the validation set up like below.

Wrapping Up

Thanks for reading! I hope this article was helpful for you to get started working with the React Hook Form library.

It is easy to use, good for performance, and requires a lot less code. Give it a shot in your next application where a form is needed.

If you want to check out the full source code for the example we created, check out the GitHub repository here.

To learn about another useful React library, check out the article below where we look at the React Icons library.

JavaScript
React
React Hook Form
Forms
Programming
Recommended from ReadMedium
avatarMykhailo Hrynkevych
Forms in React: Formik

3 min read