8 Most used NPM packages for React
React, a popular JavaScript library for building UI (user interfaces), offers a vast ecosystem of packages to enhance development efficiency and functionality. React allows developers to utilize individual parts of their application on both the client side and the server side, which ultimately boosts the speed of the development process.
Table of Content
- React-router-dom:
- Axios:
- React-Redux:
- Formik:
- React-boostrap:
- React-icons:
- React-datepicker:
- React-slick:
React-router-dom:
That package is for handling routing in React applications. It also allows you to create dynamic, single-page applications with multiple views.
Syntax to Install:
npm install react-router-dom
Example: Imported `Routes` along with Route from react-router-dom, and wrapped the <Route> components with <Route> element. Used the ‘element’ prop instead of the ‘component’ prop for specifying the component to render.
// App.js
import React from "react";
import { BrowserRouter as Router,
Routes, Route, Link }
from "react-router-dom";
const Home = () => <h2>Home</h2>;
const About = () => <h2>About</h2>;
const App = () => (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Routes>
{" "}
{/* Wrap your Route components with Routes */}
<Route path="/" element={<Home />} />{" "}
{/* Use `element` prop instead of `component` */}
<Route path="/about" element={<About />} />{" "}
{/* Use `element` prop instead of `component` */}
</Routes>{" "}
{/* Close the Routes element */}
</div>
</Router>
);
export default App;
Output:
Axios:
A popular HTTP client for making AJAX requests in the browser and NodeJS. Axios provides a smple and intuitive interface for handling asynchronous data fetching,error handling and many more.
Syntax to Install:
npm install axios
Example: Below is an example of axios.
//App.js
import React, {
useState,
useEffect
} from "react";
import axios from "axios";
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
// Define a function to fetch data from the API
const fetchData = async () => {
try {
// Make a GET request to the API endpoint
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
// Extract the data from the response
setData(response.data);
} catch (error) {
// Handle any errors that occur during the request
console.error("Error fetching data:", error);
}
};
// Call the fetchData function when the component mounts
fetchData();
// Clean up any resources when the component unmounts
return () => {
// Optionally, perform any cleanup tasks here
};
}, []);
return (
<div>
<h1>Beginnerforgeek</h1>
<ul>
{data.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default App;
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'; // Import the App component from the App.js file
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Output:
React-Redux:
That is state container for managing the state of react applications. React-Redux facilitates centralized management and enables efficient data flow across components.
Syntax to Install:
npm install redux react-redux
Example: Below is an example of creating a React-Redux.
import React from "react";
import { createStore } from "redux";
import { Provider, connect } from "react-redux";
// define the action means increament and decrement
const increment = () => ({ type: "INCREMENT" });
const decrement = () => ({ type: "DECREMENT" });
// Reduce a increment and decrement count
const counterReducer = (state = { count: 0 }, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
};
// store the all value
const store = createStore(counterReducer);
const Counter = ({ count, increment, decrement }) => {
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
// Map state to props
const mapStateToProps = (state) => ({
count: state.count,
});
// Map dispatch to props
const mapDispatchToProps = {
increment,
decrement,
};
// Connected Counter Component
const ConnectedCounter = connect(mapStateToProps, mapDispatchToProps)(Counter);
const App = () => {
return (
<Provider store={store}>
<div className="App">
<ConnectedCounter />
</div>
</Provider>
);
};
export default App;
Formik:
Formik is versatile form library for library for React and React native,design to simplify the process of building and manageing complex forms.
Syntax to Install:
npm install formik
Example: Below is an example of Formik.
import React from "react";
import { Formik, Form, Field, ErrorMessage } from "formik";
const MyForm = () => {
return (
<div>
<h1>Beginnerforgeek Form</h1>
<Formik
initialValues={{ email: "", password: "" }}
validate={(values) => {
const errors = {};
if (!values.email) {
errors.email = "Required";
} else if (
!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i
.test(
values.email
)
) {
errors.email = "Invalid email address";
}
return errors;
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>
{({ isSubmitting }) => (
<Form>
<div>
<label htmlFor="email">Email </label>
<Field type="email" name="email" />
<ErrorMessage name="email"
component="div" />
</div>
<div>
<label htmlFor="password">Password</label>
<Field type="password" name="password" />
<ErrorMessage name="password"
component="div" />
</div>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
)}
</Formik>
</div>
);
};
export default MyForm;
Output:
React-boostrap:
A library of reusable UI components for React, based on the popular Boostrap framework. React Boostrap provides a wide range of responsive and mobile first components, enabling developers to create elegant and responsive user interfaces with ease.
Syntax to Install:
npm install react-bootstrap bootstrap
Example:
import React from 'react';
import Button from 'react-bootstrap/Button';
const Example = () => (
<>
<Button variant="primary">w3wiki</Button>{' '}
<Button variant="outline-secondary">w3wiki</Button>{' '}
<Button variant="danger">w3wiki</Button>{' '}
</>
);
export default Example;
Output:
React-icons:
A collection of popular icon libraries (such as Font Awesome, Material Icons, etc.) as React components. It simplifies the process of adding icons to your React applications.
Syntax to Install:
npm install react-icons
Example: Below is an example of React-icons.
import React, { useState } from 'react';
import {
TiWeatherCloudy,
TiWeatherSunny,
TiWeatherStormy
} from 'react-icons/ti';
const WeatherApp = () => {
const [weather, setWeather] = useState('sunny');
const changeWeather = (condition) => {
setWeather(condition);
};
return (
<div className="weather-app">
<h1>Weather App</h1>
<div className="weather-container">
<h2>Current Weather:</h2>
{
weather === 'sunny' &&
<TiWeatherSunny size={100} />
}
{
weather === 'cloudy' &&
<TiWeatherCloudy size={100} />
}
{
weather === 'stormy' &&
<TiWeatherStormy size={100} />
}
<button
onClick={() => changeWeather('sunny')}>
Sunny
</button>
<button
onClick={() => changeWeather('cloudy')}>
Cloudy
</button>
<button
onClick={() => changeWeather('stormy')}>
Stormy
</button>
</div>
</div>
);
};
export default WeatherApp;
Output:
React-datepicker:
A customizable date picker component for React. It provides a simple and intuitive interface for selecting dates in forms and other user interfaces.
Syntax to Install:
npm install react-datepicker
Example: Below is an example of React-datepicker.
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
const MyDatePicker = () => {
const [selectedDate, setSelectedDate] = useState(null);
const handleDateChange = date => {
setSelectedDate(date);
};
return (
<div>
<h1>Date Picker Example</h1>
<DatePicker
selected={selectedDate}
onChange={handleDateChange}
dateFormat="dd/MM/yyyy"
placeholderText="Select a date"
/>
</div>
);
}
export default MyDatePicker;
Output:
React-slick:
A carousel/slider component for React that supports responsive design, infinite looping, and various transition effects. It’s widely used for creating image galleries, testimonials sections, and other interactive elements
Syntax to Install:
npm install react-slick slick-carousel
Example: Below is an example of React-slick.
import React from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
const MyCarousel = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
initialSlide: 1
}
}
]
};
return (
<div>
<h1>React Slick Example</h1>
<Slider {...settings}>
<div>
<h3>Gfg Slide 1</h3>
</div>
<div>
<h3> Gfg Slide 2</h3>
</div>
<div>
<h3>Gfg Slide 3</h3>
</div>
{/* Add more slides here */}
</Slider>
</div>
);
}
export default MyCarousel;
Output: