- We'll make a simple image slider in this tutorial. Multiple images can be shown using image sliders on your website.
- We'll start by importing all of the necessary files to the component where we'll be running the slideshow. We'll use the App component for this project.
- The images to use, style.css, and the useState hook will all be imported. If you're unfamiliar with the useState hook, it's a hook that allows you to add React state to function components. For additional information on hooks and useState, see the state documentation. reactjs.org/docs/hooks-state.html
- All of the images will be stored in an array within our App function. We also create a state to keep track of the activeImage. For the first image, the useState is set to 0.
- We will use two functions, next and previous, to slide the photos back and forth.
- If the activeImage is less than the length of the images, the next function will increase the image count until it reaches the last image, at which point it will stop.
- If the activeImage is greater than zero, the previous function decreases the picture count by one and then stops when it reaches the first image.
- The functions must then be passed to the previous and next buttons as onclick event listeners, while the images must be passed to the source and include the activeImage.
- Take a look at the code and the finished product below.
App.js
import "./styles.css";
import {useState} from 'react';
import sweater1 from "./imgs/sweater1.png";
import sweater2 from "./imgs/sweater2.png";
import sweater3 from "./imgs/sweater3.png";
import sweater4 from "./imgs/sweater4.png";
export default function App() {
const images = [sweater1, sweater2, sweater3,sweater4];
const [activeImage, setActiveImage] = useState(0);
function next(){
if(activeImage < 3){
setActiveImage(activeImage + 1)
}else{
setActiveImage(3)
}
}
function previous(){
if(activeImage > 0){
setActiveImage(activeImage-1)
}else{
setActiveImage(0)
}
}
return (
<div className="App">
<h1>How to make an image slider in ReactJS</h1>
<button onClick={previous} >prev</button>
<img
src={images[activeImage]}
alt='shirt'
width='50%'
height="200px"
/>
<button onClick={next} >next</button>
</div>
);
}