Take the React form library Formik as an example to talk about what a good three-party library should look like

Recently, I re- reviewed the content of the official React document about the form . At the end, when the official discussion of the mature React community form library, the Formik was  handpicked  , which caught my attention.

If you’re looking for a complete solution including validation, keeping track of the visited fields, and handling form submission, Formikis one of the popular choices

React official hand-picked library, don’t you learn to keep it as winter homework?

I read through  Formik's official documents and tried it out in the project. I 'm happy! —— "This form library is too good!"

I personally think that good third-party libraries need to meet four standards, and Formik satisfies them perfectly.

1cadd777aa599ede2baffec56c27c9ce.jpeg

One, friendly documentation

The friendliness of Formik's official documentation  is simply amazing.

The first is the overview, which briefly explains the author’s creative motivation, the basic installation process, the hello world playground, and a few basic sample codes.

But what surprised me more was the second chapter  tutorial  . This chapter takes the creation of a complete and complex  news subscription registration form  as an example, and teaches readers how to use Formik step by step. From the most basic form function, to the verification function, to tracking only the modified items; then, it further introduces Formik's multiple writing methods on the grounds of optimizing code (reducing boiler code); finally, it also introduces how to customize the form components.

I think the second chapter is a very good and standard tutorial. The content of the document is from the shallower to the deeper, layer by layer, and it has both use cases and instructions.

Before I learned about Formik, I actually had several problems in my mind, and they were all solved one by one when reading the document. This feeling made me very comfortable, and it fully demonstrated that the potential problems of most users have been considered when writing the document.


Second, keep up to date and follow the trend of the community

There are many library authors who have gradually reduced the frequency of maintenance projects, and even gave up following the trend of the community. For example,  formsy-react (the form library used before my project) does not seem to be adapted to React Hooks —— As we all know, the React community is constantly developing in the direction of React Hooks.

In contrast, in the sample code in the tutorial, Formik uses Hooks as soon as it appears-it can be said to be very "fashionable"

  // Pass the useFormik() hook initial form values and a submit function that will
  // be called when the form is submitted
  const formik = useFormik({
    initialValues: {
      email: '',
    },
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });

The front-end projects I am responsible for are constantly refactoring and evolving. Later, more and more functional components and hooks will be used. When I saw the documentation, I immediately felt that "Formik seems to be a good new form. Library selection".


Three, flexible enough

React has always been known for its flexibility. This design idea goes deep into React and should go deep into React developers. When choosing a third-party library, I will also consider whether it is flexible enough.

Formik demonstrates its flexibility in many aspects:

  • Formik's operation of the form conforms to the method recommended by the official React document-the form of a  controlled component . The advantage of this form is that the state of React becomes a single source of truth, avoiding ambiguity; in addition, obtaining the current form value is more direct and Safety. In contrast, other form libraries such as  react-hook-form  embrace the form of uncontrolled components. I personally find that it lacks a certain degree of flexibility (words are difficult to express clearly, and interested readers can try two solutions by themselves; There are also discussions in the comment area, welcome to join). 
    I wrote a related article, welcome to read

FreewheelLee: As expected, I still like whiter-white box form vs black box form in React developmentzhuanlan.zhihu.com

  • Customized form verification method: Formik's form verification logic is completely open to users, and users can customize, such as
// A custom validation function. This must return an object
// which keys are symmetrical to our values/initialValues
const validate = values => {
  const errors = {};
  if (!values.firstName) {
    errors.firstName = 'Required';
  } else if (values.firstName.length > 15) {
    errors.firstName = 'Must be 15 characters or less';
  }

  if (!values.email) {
    errors.email = 'Required';
  } else if (!isValidCompanyInternalEmail(values.email)) {
    // 是不是符合公司内部邮件的格式
    errors.email = 'Invalid email address';
  }

  return errors;
};

Formik form validation also naturally supports the Yup  library which is very popular in the community 

 const formik = useFormik({
    initialValues: {
      firstName: '',
      lastName: '',
      email: '',
    },
    validationSchema: Yup.object({
      firstName: Yup.string()
        .max(15, 'Must be 15 characters or less')
        .required('Required'),
      lastName: Yup.string()
        .max(20, 'Must be 20 characters or less')
        .required('Required'),
      email: Yup.string()
        .email('Invalid email address')
        .required('Required'),
    }),
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });
  • Support multiple usage methods: In addition to using the most direct hook, Formik uses React Context to create some components such as <Formik />, <Form />, <Field /> to simplify the code, such as
 <Formik
      initialValues={{ firstName: '', lastName: '', email: '' }}
      validationSchema={Yup.object({
        firstName: Yup.string()
          .max(15, 'Must be 15 characters or less')
          .required('Required'),
        lastName: Yup.string()
          .max(20, 'Must be 20 characters or less')
          .required('Required'),
        email: Yup.string()
          .email('Invalid email address')
          .required('Required'),
      })}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting (false);
        }, 400);
      }}
    >
      <Form>
        <label htmlFor="firstName">First Name</label>
        <Field name="firstName" type="text" />
        <ErrorMessage name="firstName" />
        <label htmlFor="lastName">Last Name</label>
        <Field name="lastName" type="text" />
        <ErrorMessage name="lastName" />
        <label htmlFor="email">Email Address</label>
        <Field name="email" type="email" />
        <ErrorMessage name="email" />
        <button type="submit">Submit</button>
      </Form>
    </Formik>
  • Flexible support for third-party component libraries, such as Material UI and Antd, which are very popular in the industry. In addition to a dedicated library derived (see document  HTTPS: // jaredpalmer.com/formik/ docs / 3rd-Party-Bindings  ), Formik designed to be very flexible because of their (controlled components), convergence of direct third-party libraries is not difficult , If it can be used like this for Material UI, it is very natural
        <TextField
            error={!_.isEmpty(formik.errors.subject)}
            helperText={_.isEmpty(formik.errors.subject) ? "" : formik.errors.subject}
            fullWidth
            label="Subject"
            name="subject"
            variant="outlined"
            className="ml-16 mt-16 mb-8 flex-grow"
            onChange={formik.handleChange}
            value={formik.values.subject}
            required
            focused
        />

In contrast, the react-hook-form  solution is slightly stiff.


Fourth, high-quality source code

After confirming that Formik is good enough at the application level, I went to look at its source code, such as the core  Formik.tsx

The code is very standardized, clean, and there are not so many bells and whistles. As long as you have enough knowledge of React and React Hooks, it is easy to read.

This makes me more confident to use this library-even if there are niche functional requirements that it cannot support in the project, I may be able to modify the source code to solve the problem by myself .

efa520d837f64a0d829561eae6917664.jpeg



The above four points are my own standards for excellent third-party libraries. Looking at these four points allows me to identify useful third-party libraries and avoid misuse of cheating third-party libraries.

In addition, these four standards also urge and warn me that I must try my best to follow them when writing my own tool library/tool ​​code, so that my code will become better and better and gradually approach the open source standard.

Finally, there are still two commonplace suggestions:

  • Learning techniques to root planted in the official documentation and source code , and then consider a third-party blog
  • Try to improve your English level and be able to read English documents when Chinese translation is lacking

b2e42f9dd3d270b50153a98da82b9e51.jpeg



Regarding the dispute between controlled and uncontrolled components, I wrote an article, welcome to read

FreewheelLee: As expected, I still like whiter-white box form vs black box form in React developmentzhuanlan.zhihu.com



Reference link:

  1. https://reactjs.org/docs/forms.html#controlled-components
  2. https://jaredpalmer.com/formik/docs/tutorial
  3. https://github.com/jaredpalmer/formik/blob/master/packages/formik/src/Formik.tsx
  4. https://github.com/jquense/yup


Guess you like

Origin blog.51cto.com/15064417/2569720