😎 How to convert a normal React form to use react-hook-form?

maxprogramming

Max Programming

Posted on November 8, 2021

😎 How to convert a normal React form to use react-hook-form?

Hey everyone!

Nice to see you all around again! Today you'll find out how easy it is to use the react-hook-form library for forms instead of the normal method of forms in React.

image.png

So, the first thing is first, normally, in React we use state, and whenever the value of an input changes, we change the state. This method's good but there is a lot of code. Here's how the code looks like in this case.

import { useState } from 'react';

export default function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const onSubmit = (e) => {
    e.preventDefault()
    // Submit logic
  }

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input
          type='email'
          value={email}
          onChange={e => setEmail(e.target.value)}
        />
        <input
          type='password'
          value={password}
          onChange={e => setPassword(e.target.value)}
        />
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

And I personally feel that this is indeed a lot of code that could be made better. That's why you should use react-hook-form.

So to convert this normal one to use react-hook-form, we install it via NPM or Yarn.

npm i react-hook-form
# yarn add react-hook-form
Enter fullscreen mode Exit fullscreen mode

And then, the first thing we have to do is get rid of the state we created, the onSubmit function and the value and onChange props too.

After we remove that bit of code, we import useForm from react-hook-form, and this is how we use it.

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

export default function LoginForm() {
  const { register, handleSubmit } = useForm();

  return (
    <div>
      <form>
        <input type='email' />
        <input type='password' />
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Then, we use the register function as a prop in the inputs to register each input with a name to get the value of it, like this.

return (
  <div>
    <form>
      <input type='email' {...register('email')} />
      <input type='password' {...register('password')} />
    </form>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Then, for the form submission, we use the handleSubmit provided by the useForm hook with our own submit function which provides us the values of the inputs directly. We can also destructure the values from it.

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

export default function LoginForm() {
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => { // OR DESTRUCTURING ({ email, password })
    console.log(data.email, data.password)
    // Submit logic
  }

  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}> {/* handleSubmit is invoked and onSubmit is passed into it */}
        <input type='email' {...register('email')} />
        <input type='password' {...register('password')} />
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This way, it automatically prevents the page from refreshing on submit.

πŸ’ͺ Using it with TypeScript

Using RHF with TypeScript is super easy because firstly, you don't need to install separate type definitions as they come along with RHF.

You've to define an interface for the fields you're using, and then pass it in useForm as generic.

interface LoginFields {
  email: string;
  password: string;
}

// In component
const { register, handleSubmit } = useForm<LoginFields>();
Enter fullscreen mode Exit fullscreen mode

And while calling the submit function, you've to set the type of the onSubmit function to the type SubmitHandler provided directly by RHF.

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

// In component
const onSubmit: SubmitHandler<LoginFields> = ({ email, password }) => { 
    console.log(email, password)
    // Submit logic
  }
Enter fullscreen mode Exit fullscreen mode

This way you also get good IntelliSense in your IDE or code editor
intellisense.gif

Conclusion

You can read a lot more functionalities provided by react-hook-form on their website.

I hope you liked it! Comment down your thoughts! There is always room for improvement so let me know your suggestions on this project!

Connect with me on my YouTube channel and my Twitter πŸ˜‰

Until next time, keeping awesome ✌️

πŸ’– πŸ’ͺ πŸ™… 🚩
maxprogramming
Max Programming

Posted on November 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related