While working on web applications, we commonly need to show multiple images with the help of a slider.
In this article, We will see how to create an image slider with Carousel in React.js application. We will use here an npm package.
Run below command to create a basic react app
npx create-react-app react-carousel-app
Now move to the project folder, with below command
cd react-carousel-app/
Run below command inside project folder to install the needed package for the carousel slider
npm install react-responsive-carousel --save
create a file named carousel.js inside the src folder, you can put it wherever you prefer. Insert below code in the component file created.
We need to do below tasks in this component
1. Import carousel package
import { Carousel } from 'react-responsive-carousel';
2. Import the carousel CSS fil
import "react-responsive-carousel/lib/styles/carousel.min.css";
3. Insert 3 images inside public folder to show in the slider
Now the final code inside the carousel component will look like below:
import CarouselComponent from "./carousel";
Now check the carousel added in the react.js application after running it with below command:
npm start
If everything is done correctly, the app will look like below:
We have successfully created a basic slider within React.js application using the Responsive Carousel package, It's a simple slider with the thumbnail and previous and next option.
Keyboard control, Infinite Loop and Autoplay feature can be added easily with this package.
<Carousel infiniteLoop useKeyboardArrows autoPlay>
....
....
....
</Carousel>
Keyboard Control: After adding this, keyboard next previous keys will be used in the slider
Infinite Loop: This feature adds the feature to loop the images infinitely
Auto Play: It makes the slider running automatically without manual intervention.
There are huge list of methods available with this npm package to modify the carousel slider. Click here to see all the lists on the official website.
We just created a basic Carousel Slider using react responsive carousel package.
You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.
That’s all for now. Thank you for reading and I hope this article helped you.
Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Find complete source code over GitHub