4 libraries that simplify the life of a React-developer


In this article I will talk about four libraries that will make your life easier. At least I hope so

1) Nanoid

Link to github
This is a small library that has only one function - the generation of a unique id. It can be useful in most cases, like any other generator of random sequences of characters. Undeniable advantages: simplicity and tiny size - 143 bytes .

Of course, if you use, for example, lodash, then you can use the uniqueId () method.
Using as simple as possible:
import nanoid from'nanoid'
size = 8
id = nanoid(size) //cjF38yYc

NEVER use nanoid () to index lists or any other duplicate items using key in ReactJS. As if using this method, every time when updating a component, React will think that all elements are new and will re-render them, which will have a very bad effect on performance and generally contradict the meaning of key.

Learn more about key: reactjs.org/docs/lists-and-keys.html#keys
More details about key: habr.com/company/hh/blog/352150

An example of very bad use of nanoid:
import nanoid from'nanoid'import React from'react'const ListDrinks = props=>{
    const drinks = ['rum','bear','vodka']
                //Вот так делать нельзя!
exportdefault ListDrinks

An example of normal use of nanoid:
import React, { Component } from'react';
import nanoid from'nanoid'classInputWithLabelextendsComponent{
    this.id = nanoid()
  render() {
    return (
      <div><labelhtmlFor={this.id}>My label</label><inputid={this.id}type="text"/></div>
export default InputWithLabel;

How I can’t do it, I learned from kind people in the comments, for which they are special, thank you very much!

2) Classnames

Link to github
This library is for simple conditional combining of class names. It is not much more difficult to use than the previous library.

An example of simple use:

import cn from'classnames'
cn('menu','active')//'menu active'let isActive = true
cn('menu',{'active':isActive})//'menu active'
isActive = false

For me personally, this library is mandatory in any React application. Of course, until I find a more convenient tool.

3) Formik and Yup

Link to github (Formik)
Link to github (Yup)
In the conversation about the simplification of something in React not to mention the work with forms. Probably every beginner of React-developer at one point understood how he hates working with forms. When this understanding comes, you should immediately look for a saving pill.

For me, this pill was Formik and Yup.

Formik is a library that helps work with forms. It makes it easy to get data from a form, validate data, display error messages, and more.

Yup is the library that is the validator for the model that we ourselves create using Yup.

For any complete description of this bundle, a separate article is needed, but I will try to show from a bird's eye view what they are.

The example code can be run here: Example

First, create a schema:

import * as Yup from"yup";
const BasicFormSchema = Yup.object().shape({
  email: Yup.string()
    //Проверяем, корректный ли адрес.//Если нет, то выводится сообщение в скобках
    .email("Invalid email address")
    //не сабмитим, если поле не заполнено
  username: Yup.string()
    //минимальная длина - 2 символа
    .min(2, "Must be longer than 2 characters")
    //максимальная длина - 20 символов
    .max(20, "Nice try, nobody has a first name that long")
  password: Yup.string()
    .min(8, "Must be longer than 8 characters")
exportdefault BasicFormSchema;

In the code above, we defined a scheme that is essentially an object. It has three fields: email, username and password. For each of the fields, we have identified some checks.

One way to use Formik is the <Formik /> element, which has many different properties, one of which is render .

import React from"react";
import { Formik, Field, Form } from"formik";
import BasicFormSchema from"./BasicFormSсhema";
const SignUp = () => (
  <div className="container">
    <h1>Sign up</h1>
      //инициализируем значения input-ов
        email: "",
        username: "",
        password: ""
      //подключаем схему валидации, которую описали выше
      //определяем, что будет происходить при вызове onsubmit
      onSubmit={values => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
        }, 500);
      //свойство, где описывыем нашу форму
      //errors-ошибки валидации формы
      //touched-поля формы, которые мы "затронули",
      //то есть, в которых что-то ввели
      render={({ errors, touched }) => (
        <Form className="form-container">
          <label htmlFor="email">Email</label>
          {//если в этом поле возникла ошибка и 
          //если это поле "затронуто, то выводим ошибку
            errors.email &&
            touched.email && <div className="field-error">{errors.email}</div>}
          <label htmlFor="username">Username</label>
          <Field name="username" placeholder="snapoak" type="text" />
          {errors.username &&
            touched.username && (
              <div className="field-error">{errors.username}</div>
          <label htmlFor="password">Password</label>
          <Field name="password" placeholder="123456qwe" type="password" />
          {errors.password &&
            touched.password && (
              <div className="field-error">{errors.password}</div>
          <button type="submit">Submit</button>
export default SignUp;

The code is simple, I provided it with comments, so I think there shouldn't be any questions.
If they have arisen, then there is excellent documentation in the GitHub repository, you can also ask questions in the comments.

That's the end. I know that there are many excellent libraries for working with forms, some seem to you the best, some worse. I expressed my personal opinion here.

Hope this article can anyone. You can write your own examples of useful libraries in the comments, I will be glad to learn something new.

Also popular now: