Introduction to React
In the world of modern web development, React stands out as a powerful and versatile library for building user interfaces. Developed by Meta (formerly Facebook), React has gained immense popularity among developers and is widely used in various applications.
What is 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 that can be composed together to build complex applications.
React in Action
React is widely used in the development of popular websites and web applications, including:
- Netflix
- Airbnb
- WhatsApp Web
- Twitch
Exploring React Libraries
What is a Library?
In coding, a library refers to a collection of pre-written code that developers can leverage to simplify and expedite their programming tasks. These libraries provide reusable functionality that can be integrated into different applications, reducing development time and effort.
Library will help you in less coding and effort
Essential Libraries for React Development
1. Axios
npm i axios
Axios is a simple promise based HTTP client for the browser and node.js. Axios provides a simple-to-use library in a small package with a very extensible interface.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
Instead of using Fetch we can use Axios and reduce the line of code by hitting API with the Axios library
2. Formik:
Formik is a free, open-source library that helps build and process form data in React applications. It provides a simple API and built-in validation, making it easy to collect and manipulate input data. Formik is used by companies like Airbnb, Walmart, Lyft, and Stripe.
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;
Formik simplifies form validation in React applications by providing an intuitive API for managing form state and validation logic.
3. React Helmet
React Helmet, for instance, can be used to dynamically set the document’s title, description, and meta tags. This comes in very handy when you need to update the meta tags for SEO. React Helmet supports all valid head tags, including title, style, base, meta, link, script, and NoScript.
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>
);
}
};
React Helmet can help you improve the SEO of your website by making it easier to set and update the meta tags that search engines use to index and rank your pages. By providing accurate and up-to-date information about your content, you can help search engines understand your website better and improve your ranking in search results.
React Helmet can also help you enhance the social media sharing of your website by making it easier to set and update the meta tags that social media platforms use to display your content when it is shared.
4. React-Redux:
Redux is a JS library for predictable and maintainable global state management.
npm i react-redux
Basic Example of React-Redux
import React from 'react';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
// Define the initial state
const initialState = {
count: 0
};
// Define reducer function
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
...state,
count: state.count + 1
};
case 'DECREMENT':
return {
...state,
count: state.count - 1
};
default:
return state;
}
};
// Create the Redux store
const store = createStore(reducer);
// Define action creators
const increment = () => ({ type: 'INCREMENT' });
const decrement = () => ({ type: 'DECREMENT' });
// Counter component
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
// Connect Counter component to Redux store
const ConnectedCounter = connect(
state => ({ count: state.count }),
{ increment, decrement }
)(Counter);
// App component
const App = () => {
return (
<Provider store={store}>
<ConnectedCounter />
</Provider>
);
};
export default App;
The whole global state of your app is stored in an object tree inside a single store. The only way to change the state tree is to create an action, an object describing what happened, and dispatch it to the store. To specify how a state gets updated in response to an action, you write pure reducer functions that calculate a new state based on the old state and the action.
5. React Router DOM
npm i react-router-dom
React Router Dom is commonly used for routing and managing navigation in web applications built using React. It simplifies the routing process by providing an API to define, navigate, and render routes.
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
import "./index.css";
const router = createBrowserRouter([
{
path: "/",
element: <div>Hello world!</div>,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
The major advantage of react-router is that the page does not have to be refreshed when a link to another page is clicked…
6. Dotenv:
npm install dotenv --save
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from the codebase to secure the keys and information that should be kept confidential like passwords and secret key
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;
7. esLint
npm i eslint
ESLint is a popular open-source JavaScript linting utility. It analyzes your code for potential errors, enforces coding standards, and improves code quality. ESLint can also help you as a developer to identify and fix common mistakes, use best practices, and maintain consistency across your codebase.
Basic example
import js from "@eslint/js";
export default [
js.configs.recommended,
{
rules: {
"no-unused-vars": "warn",
"no-undef": "warn"
}
}
];
import React from 'react';
import Header from './components/Header';
const App = () => {
return (
<div>
<Header />
</div>
);
};
export default App;
As you can see, all we want to do is to render that one component. But if we run eslinton this file, we'll get a couple of errors.
1:8 warning 'React' is defined but never used no-unused-vars
2:8 warning 'Header' is defined but never used no-unused-vars
8. date-fns
npm i date-fns
date-fns provides the most comprehensive, yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.
// 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);
Date-fns is a powerful and versatile library for working with dates and times in JavaScript. It is a great choice for projects of all sizes.
9. react-error-boundaries
npm install react-error-boundary
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed
The component supports several ways to render a fallback (as shown below).
"use client";
import { ErrorBoundary } from "react-error-boundary";
function fallbackRender({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
return (
<div role="alert">
<p>Something went wrong:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
</div>
);
}
<ErrorBoundary
fallbackRender={fallbackRender}
onReset={(details) => {
// Reset the state of your app so the error doesn't happen again
}}
>
<ExampleApplication />
</ErrorBoundary>;
Wrap an ErrorBoundary component around other React components to "catch" errors and render a fallback UI (A fallback UI is a temporary UI that renders in place of the actual UI when it hasn’t finished loading).
10. sweetalert
npm install sweetalert --save
SweetAlert is a JavaScript library that provides alternative alert and modal dialog boxes for web applications. It can replace built-in alert functions and improve the user interface of default browser dialogs.
import React from 'react';
import Swal from 'sweetalert';
const SweetAlertExample = () => {
const handleClick = () => {
Swal.fire({
title: 'Hello!',
text: 'This is a SweetAlert dialog.',
icon: 'success',
confirmButtonText: 'OK'
});
};
return (
<div>
<h1>SweetAlert Example</h1>
<button onClick={handleClick}>Show SweetAlert</button>
</div>
);
};
export default SweetAlertExample;
11. styled-components
npm i styled-components
Styled-components is an open-source library that allows React and React Native developers to define UI components and styles in a single file location. It uses CSS in JavaScript (JS), which allows developers to write CSS code directly in the JavaScript file.
import React from 'react';
import styled from 'styled-components';
// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
function MyUI() {
return (
// Use them like any other React component – except they're styled!
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
</Wrapper>
);
}
- react-tooltip
npm install react-tooltip
The react-tooltip package provides a component that can be bound to an anchor element and used to display element-specific information.
import React from 'react';
import ReactTooltip from 'react-tooltip';
const TooltipExample = () => {
return (
<div>
<h1>React Tooltip Example</h1>
<button data-tip="Hello, I am a tooltip!" data-for="tooltip">Hover me</button>
<ReactTooltip id="tooltip" place="bottom" effect="solid" />
</div>
);
};
export default TooltipExample;
13. React Spinner
npm install --save react-spinners
react-spinner-loader provides a simple React SVG spinner component which can be implemented for async-await operation before data loads to the view.
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;
14. Yup
npm i yup
Yup is a schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup, schema are extremely expressive and allows modeling complex, interdependent validations, or value transformation.
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)),
});
15. @testing-library/jest-dom
npm install --save-dev @testing-library/jest-dom
@testing-library/jest-dom
is a library that provides custom matchers to test the state of the DOM. It’s an extension for the Jest testing framework that enables assertions on DOM elements, attributes, and content.
<button data-testid="button" type="submit" disabled>submit</button>
<fieldset disabled><input type="text" data-testid="input" /></fieldset>
<a href="..." disabled>link</a>
expect(getByTestId('button')).toBeDisabled()
expect(getByTestId('input')).toBeDisabled()
expect(getByText('link')).not.toBeDisabled()
Conclusion
By leveraging these libraries, developers can enhance the functionality, performance, and user experience of their React applications while reducing development time and effort.
Overall, this comprehensive overview provides valuable insights into the ecosystem of tools and libraries available for React development, empowering developers to build robust and feature-rich applications effectively.
Top comments (0)