Max RozenTwitter
AboutNewsletter

Frustrated by Formik? Here's a simpler way to do forms in React

Is this you?

I’ve tried so many different things I’ve found online

Holy crap it works now, such a small problem I’ve lost hours to :(

All I want to do is a simple thing, this is all so unnecessarily complex

Try using react-hook-form.

React-hook-form is different, because it (mostly) keeps its state in the DOM (like classic HTML form elements).

Here’s an example of a single field form in react-hook form (taken from their docs):

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

const Example = () => {
  const { handleSubmit, register, errors } = useForm();
  const onSubmit = (values) => console.log(values);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="email"
        ref={register({
          required: 'Required',
          pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
            message: 'invalid email address',
          },
        })}
      />
      {errors.email && errors.email.message}

      <input
        name="username"
        ref={register({
          validate: (value) => value !== 'admin' || 'Nice try!',
        })}
      />
      {errors.username && errors.username.message}

      <button type="submit">Submit</button>
    </form>
  );
};

Compare that to your existing form code. I don’t know about you, but my React forms with Formik would have twice as many lines of code to achieve the same thing.

You’ll notice that it’s using ref, rather than tracking state within the library. Since moving to react-hook-form, I no longer have to worry about state not syncing correctly in huge forms.

Everything just works as expected, and my code is much simpler too.

Get The Newsletter!

    No spam, ever.

    Unsubscribe at any time.

    WebMentions

    12 ❤️
    2 💬
    Peter Hanssens replied on Thu Jul 23 2020
    Nice yeah I had this issue - Formik and react hooks just seemed like a massive overkill
    miko replied on Thu Jul 23 2020
    i needed this this morning
    No further replies found. Tweet about this post and it will show up here!
    rssTwitterGitHub

    © 2020 Max Rozen. All rights reserved.