😎 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.

So, the first thing is first, normally, in React we use st…


This content originally appeared on DEV Community and was authored by Max Programming

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>
  );
}

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

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>
  );
}

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>
);

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>
  );
}

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>();

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
  }

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 ✌️


This content originally appeared on DEV Community and was authored by Max Programming


Print Share Comment Cite Upload Translate Updates
APA

Max Programming | Sciencx (2021-11-08T09:11:34+00:00) 😎 How to convert a normal React form to use react-hook-form?. Retrieved from https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/

MLA
" » 😎 How to convert a normal React form to use react-hook-form?." Max Programming | Sciencx - Monday November 8, 2021, https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/
HARVARD
Max Programming | Sciencx Monday November 8, 2021 » 😎 How to convert a normal React form to use react-hook-form?., viewed ,<https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/>
VANCOUVER
Max Programming | Sciencx - » 😎 How to convert a normal React form to use react-hook-form?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/
CHICAGO
" » 😎 How to convert a normal React form to use react-hook-form?." Max Programming | Sciencx - Accessed . https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/
IEEE
" » 😎 How to convert a normal React form to use react-hook-form?." Max Programming | Sciencx [Online]. Available: https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/. [Accessed: ]
rf:citation
» 😎 How to convert a normal React form to use react-hook-form? | Max Programming | Sciencx | https://www.scien.cx/2021/11/08/%f0%9f%98%8e-how-to-convert-a-normal-react-form-to-use-react-hook-form/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.