r/reactjs • • Mar 02 '20

Resource React Hook Form: Performant, flexible and extensible forms with easy-to-use validation

https://react-hook-form.com/
203 Upvotes

39 comments sorted by

View all comments

9

u/AiexReddit Mar 03 '20 edited Mar 04 '20

I like the look of this, but I feel like they're being disingenuous with the way they present their examples. They are making a statement saying "less lines of code is good", using a Formik example that writes:

function validateUsername(value) {
  let error;

  if (value === "admin") {
    error = "Nice try!";
  }

  return error;
}

Whereas with their library they write:

validate: value => value !== "admin" || "Nice try!"

I understand that they say "this is taken from the official documentation" but if that's the case they need to use the same coding style for their own examples to be able to make a fair comparison.

0

u/maple-factory Mar 03 '20

The whole example is disingenuous. It's easy to write a Formik example that is a few lines shorter than the React Hook Form example and just as clean:

import React from "react";
import { useFormik, Field } from "formik";

const Example = () => {
  const onSubmit = values => {
    console.log(values);
  };
  const { handleSubmit, values, errors, touched } = useFormik({
    initialValues: { username: "", email: "" },
    onSubmit
  });

  return (
    <form onSubmit={handleSubmit}>
      <Field name="email" validate={value => {
        if (!value) {
          return "Required";
        } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
          return "Invalid email address";
        }
      }} />
      {errors.email && touched.email && errors.email}

      <Field name="username" validate={value => value === "admin" || "Nice try!"} />
      {errors.username && touched.username && errors.username}

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