How to add carousel in react js?
May 02, 2024Hi Friends 👋,
Welcome To aHoisting!
To add carousel in react js, you can use <Slider {...settings}>
. It will add carousel in react js.
Today, I am going to show you, how to add carousel in react js.
Table of contents
- Install and create a new React app.
- install react-slick and slick-carousel.
- Import react component.
- Create a Component.
Let’s start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: install react-slick and slick-carousel.
To add a carousel in a React application, you can use popular libraries like react-slick and react-carousel Carousel. Here’s an example of how you can add a carousel using the react-slick library:
npm install react-slick slick-carousel
Step 3: Import react component.
After installing, you have to import your React component. To do this, add the following line to the top of your component file.
import React from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
Step 4: Create a Component.
You can set <Slider {...settings}>
to add carousel in react js.
<Slider {...settings}>
<div>
<h3>aHoisting 1</h3>
</div>
<div>
<h3>aHoisting 2</h3>
</div>
<div>
<h3>aHoisting 3</h3>
</div>
<div>
<h3>aHoisting 4</h3>
</div>
<div>
<h3>aHoisting 5</h3>
</div>
<div>
<h3>aHoisting 6</h3>
</div>
</Slider>
Define the add carousel example.
The below code is an example of a React. You have to import react-slick
and You can use <Slider {...settings}>
to add carousel in react js.
App.js
import React from 'react';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
const Carousel = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 1,
infinite: true,
dots: true
}
},
{
breakpoint: 768,
settings: {
slidesToShow: 2,
slidesToScroll: 1,
infinite: true,
dots: true
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
dots: true
}
}
]
};
return (
<Slider {...settings}>
<div>
<h3>aHoisting 1</h3>
</div>
<div>
<h3>aHoisting 2</h3>
</div>
<div>
<h3>aHoisting 3</h3>
</div>
<div>
<h3>aHoisting 4</h3>
</div>
<div>
<h3>aHoisting 5</h3>
</div>
<div>
<h3>aHoisting 6</h3>
</div>
</Slider>
);
};
export default Carousel;
In the above code example, I have used the <Slider {...settings}>
object and add carousel in react js.
Check the output of the above code example.
All the best 👍