Simple react slider
Hi guys, today I’m going to show you how to do a simple slider in react, with effects! We’re going to use the same structure of the react carousel article, so its probably best to check that out first.
Right, so the first thing we need to do is replace your App.css with the code below. We add some new classes (.animation-fade, .animation-slide-left and .animation-slide-right), with some animations using keyframes.
Now we’re going to create a new components folder inside the src, and a file called slider.jsx (src/components/slider.jsx), and copy all the App.js content inside this component. Now the App.js look like that (I’m going to explain the mode props later):
In the slider.jsx, we’re going to make some changes: add a new state to manipulate the animation class (className, setClassName), and create two new functions, to manipulate the previous and the next images. In the prevSlide function, if the activeImageIndex is 0 (the first img), we need to setActiveImageIndex to the last image index (images.length-1) to create the Infinite effect, if not, we just set the previous image index (activeImageIndex — 1). The same goes for the nextSlide, if the activeImageIndex is the last one (images.length-1), we setActiveImageIndex to 0 (the first image), if not, we set the next image index (activeImageIndex + 1).
We’re going to need a prop (mode) to check which effect we’re going to use (fade or slide), so we’re going to check which class we’re going to set in the setClassName state. The setTimeOut is to remove the className, before adding it again in the next onClick, implementing the animation effect on the image. So now the code look like that:
We’re going to change the code to behave like a normal slider, removing the thumbs and adding the prev and next buttons, calling the prevSlide and the nextSlide functions. To use the previous and next icons, we’re going to install the ‘react-icons’ package using npm install react-icons — save, and you can see on their website, libraries of icons to use, in this code we’re going to use the font-awesome one, so now, the code looks like this:
To wrap it up, we’re going to set the PropTypes to only accept two types: ‘fade’ or ‘slide’.
And that's it! If you have any doubts, here's the repo for you to see the whole code: https://github.com/supersonicgabs/react-slide, see you at the next one :)