编程知识 cdmana.com

Taking react form library formik as an example, what kind of excellent tripartite library should be

I've had a fresh brush recently React Official documents About the content of the form , At the end , Official discussion mature react Community form library   be appointed by the emperor to the Imperial Academy   了 Formik, Got 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 The official imperial Library , Don't learn to keep it for winter vacation homework ?

Read it through  Formik Official documents of , I tried it in the project , Overjoyed ! —— ” This form library is excellent too !“

I personally think that a good third-party library needs to meet four criteria ,Formik They are perfectly satisfied .

1cadd777aa599ede2baffec56c27c9ce.jpeg

One , Friendly documentation

Formik Official documents of   It's amazing how friendly it is .

First of all overview It briefly expounds Formik The author's creative motivation , The basic installation process , also hello world It's a great environment to play (playground), And some basic sample code

But what surprised me even more was chapter two  tutorial . This chapter , To create a complete and complex   News subscription registration form   For example , Step by step “ handy ” To teach readers to use Formik. From the most basic form function , To the verification function , To just track Modified ; next , To optimize the code ( Reduce template code ) For the further introduction of Formik Various writing methods ; Finally, it introduces how to customize form components .

The second chapter, I think, is a very good and standard teaching document (tutorial), The content of the document goes from simple to deep , Step by step , And it's a combination of situational use cases and descriptions .

I am understanding. Formik Before , In fact, there are several problems in my mind , It's all solved one by one while reading the document , This feeling makes me very comfortable , It fully shows that the potential problems of most users have been considered when writing the document .


Two , Keep up to date , Following the community trend

There are a lot of Library authors , Gradually reducing the frequency of maintenance projects , Even giving up the trend of following the community , such as  formsy-react( The form library I used before my project ) This library doesn't look like it's going to fit React Hooks —— And as we all know ,React The community is going to React Hooks The direction continues to develop .

In contrast ,Formik stay tutorial In the example code in , It's used as soon as it comes out Hooks —— It can be said that it is 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, null2));
    },
  });

The front-end projects I'm in charge of are also constantly refactoring 、 evolution , After that, more and more functional components will be used and Hooks, When I saw the document, I immediately felt “Formik It seems like a good choice for a new form library ”.


3、 ... and , Flexible enough

React It has always been known for its flexibility , This design idea goes deep React, It should also go deep into React developer . Choose a third-party library , I'll also consider whether it's flexible enough .

Formik It's flexible in many ways :

  • Formik The operation of the form conforms to React The way official documents recommend ——  Controlled components In the form of , The advantage of this form is to make React Of state Become single source of truth, Avoid ambiguity ; Besides , Getting the current form value is also more direct and secure . In contrast , Other form libraries like  react-hook-form  Embracing the form of uncontrolled components , I personally find that there is a lack of flexibility ( It's hard to articulate in words , Interested readers can try two solutions by themselves ; There are also comments in the discussion area , Welcome to join ). 
    I wrote an article about it , Welcome to

FreewheelLee: I really like the white one —— React White box forms in development vs Black box form zhuanlan.zhihu.com

  • Custom form validation method :Formik The form validation logic of is completely open to users , Users can customize it , 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)) {
    //  Is it in line with the company's internal mail format 
    errors.email = 'Invalid email address';
  }

  return errors;
};

Formik Form validation also naturally supports the community's very popular  Yup  library

 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, null2));
    },
  });
  • Support a variety of uses : In addition to using the most direct hook,Formik utilize React Context Some components such as <Formik />, <Form />, <Field /> So as to achieve the purpose of simplifying 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 , For example, the industry is very popular Material UI and Antd . In addition to the special derivative library ( See documentation  https://jaredpalmer.com/formik/docs/3rd-party-bindings ),Formik Because it's designed to be very flexible ( Controlled components ), It is not difficult to directly connect with the third-party library , If yes Material UI It can be used like this , It's 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 ,react-hook-form  Our solution is a bit stiff .


Four , High quality source code

In determining Formik After being good enough at the application level , I went to see its source code again , For example, the core  Formik.tsx

The code is very standard , clean , There's not so much fancy stuff , As long as there's enough React and React Hooks knowledge , It's not hard to read .

It gives me more confidence to use this library —— Even if there are small functional requirements in the project that it cannot support , I may also 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 , Identifying these four points allows me to identify beneficial third-party libraries and avoid misuse of kengda's third-party libraries .

besides , These four standards also spur and warn me , Writing your own tool library / Do your best to follow them when you code tools , Make your code better and better , Getting closer to open source standards .

Last , Still two clich é s :

  • Learning technology should be rooted in Embedded in official documents and source code , Consider third-party blogs
  • try the best Improve your English , Be able to read English documents when Chinese translation is lacking

b2e42f9dd3d270b50153a98da82b9e51.jpeg



Disputes over controlled and uncontrolled components , I wrote a special article , Welcome to

FreewheelLee: I really like the white one —— React White box forms in development vs Black box form zhuanlan.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


版权声明
本文为[osc_ 97wmavr6]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224153627262j.html

Scroll to Top