7 Libraries You Should Know if You Develop with React.


React is a free and open-source front-end JavaScript library that simplifies the process of building dynamic and interactive user interfaces. It adopts a component-based architecture, allowing developers to create reusable UI components.


What is a Library?

In programming, a library refers to a collection of pre-written that developers can use to streamline and accelerate their development process. These libraries offer reusable features that can be incorporated into various applications .

1- Formik

Formik is a free, open-source library for React applications that simplifies building and handling form data with a straightforward API and built-in validation

npm i formik
import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';

const initialValues = {
  firstName: '',
  lastName: '',
  email: '',
};

const onSubmit = (values) => {
  console.log(values);
};

const validate = (values) => {
  const errors = {};

  if (!values.firstName) {
    errors.firstName = 'Required';
  }

  if (!values.lastName) {
    errors.lastName = 'Required';
  }

  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^\S+@\S+\.\S+$/.test(values.email)) {
    errors.email = 'Invalid email address';
  }

  return errors;
};

const SampleForm = () => {
  return (
    <div>
      <h1>Sample Form</h1>
      <Formik
        initialValues={initialValues}
        onSubmit={onSubmit}
        validate={validate}
      >
        {({ isSubmitting }) => (
          <Form>
            <div>
              <label htmlFor="firstName">First Name:</label>
              <Field type="text" id="firstName" name="firstName" />
              <ErrorMessage name="firstName" component="div" />
            </div>

            <div>
              <label htmlFor="lastName">Last Name:</label>
              <Field type="text" id="lastName" name="lastName" />
              <ErrorMessage name="lastName" component="div" />
            </div>

            <div>
              <label htmlFor="email">Email:</label>
              <Field type="email" id="email" name="email" />
              <ErrorMessage name="email" component="div" />
            </div>

            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </Form>
        )}
      </Formik>
    </div>
  );
};

export default SampleForm;

2- React Helmet

React Helmet is a tool for dynamically setting the document’s title, description, and meta tags in React applications, which aids in improving SEO. By easily updating meta tags, it helps search engines better understand and index your content, potentially enhancing your search rankings.

npm i react-helmet
import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <meta charSet="utf-8" />
                <title>My Title</title>
                <link rel="canonical" href="http://mysite.com/example" />
            </Helmet>
            ...
        </div>
    );
  }
};

3- Dotenv

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. It helps secure sensitive information, such as passwords and secret keys, by keeping configuration separate from the codebase

npm install dotenv --save
import React, { useEffect, useState } from 'react';
require('dotenv').config();

const App = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Fetch data from the API using the environment variable
    fetch(process.env.REACT_APP_API_URL)
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  return (
    <div>
      <h1>Data from API</h1>
      {data ? (
        <pre>{JSON.stringify(data, null, 2)}</pre>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};

export default App;

4-  date-fns

date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.

npm i date-fns
// Parse a date string
const date = dateFns.parse('2023-08-04');

// Format a date
const formattedDate = dateFns.format(date, 'MM/dd/yyyy');

// Compare two dates
const areDatesEqual = dateFns.isEqual(date1, date2);

// Calculate the difference between two dates
const differenceInDays = dateFns.differenceInDays(date1, date2);

5- sweetalert

SweetAlert is a JavaScript library that enhances web applications by providing customizable alert and modal dialog boxes, offering a more attractive alternative to the default browser dialogs.

npm install sweetalert --save
import React from 'react';
import Swal from 'sweetalert2';

const SweetAlertExample = () => {
  const showAlert = () => {
    Swal.fire({
      title: 'Hello!',
      text: 'This is a SweetAlert dialog.',
      icon: 'success',
      confirmButtonText: 'OK'
    });
  };

  return (
    <div>
      <h1>SweetAlert Example</h1>
      <button onClick={showAlert}>Show SweetAlert</button>
    </div>
  );
};

export default SweetAlertExample;

6-  React Spinner

react-spinner-loader provides a simple React SVG spinner component which can be implemented for async-await operation before data loads to the view.

npm install --save react-spinners
import React from 'react';
import { css } from '@emotion/react';
import { RingLoader } from 'react-spinners';

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

const SpinnerExample = () => {
  return (
    <div className="sweet-loading">
      <RingLoader color={'#123abc'} css={override} size={150} loading={true} />
    </div>
  );
};

export default SpinnerExample;

7- Yup

Yup is a schema builder for runtime value parsing and validation, allowing you to define schemas, transform values, and assert the shape of existing values. Its expressive schemas support complex, interdependent validations and value transformations.

npm i yup
import * as yup from 'yup';

const personSchema = yup.object({
  firstName: yup.string().defined(),
  nickName: yup.string().default('').nullable(),
  sex: yup
    .mixed()
    .oneOf(['male', 'female', 'other'] as const)
    .defined(),
  email: yup.string().nullable().email(),
  birthDate: yup.date().nullable().min(new Date(1900, 0, 1)),
});

Post a Comment

Previous Post Next Post