Create a Dynamic Image Slider App Using React and JavaScript
Written on
Introduction to React Image Slider
React is a user-friendly JavaScript framework that simplifies building front-end applications. This guide will demonstrate how to construct an image slider app utilizing React and JavaScript.
Creating the React Project
To initiate the project, we can use Create React App. To install it, execute the following command:
npx create-react-app image-slider
This command sets up our React project environment.
Building the Image Slider App
To develop the image slider app, we will utilize the following code:
import { useState } from "react";
const images = [
];
export default function App() {
const [index, setIndex] = useState(0);
const next = () => {
setIndex((i) => (i + 1) % images.length);};
const prev = () => {
setIndex((i) => (i - 1 + images.length) % images.length);};
return (
<div className="App">
<button onClick={prev}><</button>
<img src={images[index]} alt="Current slide" />
<button onClick={next}>></button>
</div>
);
}
In the images array, we have three image URLs. The App component maintains an index state initialized to 0, which is managed by the setIndex function. The next and prev functions update the index, allowing us to navigate through the images cyclically.
To display the images, we utilize JSX, which includes buttons that trigger the next and prev functions upon clicking. The current image is shown in the img element.
Implementing Automatic Image Slider
For an automated slider that transitions between images, we can modify the code as follows:
import { useEffect, useState } from "react";
const images = [
];
export default function App() {
const [index, setIndex] = useState(0);
const next = () => {
setIndex((i) => (i + 1) % images.length);};
useEffect(() => {
const timer = setInterval(next, 1000);
return () => {
clearInterval(timer);};
}, []);
return (
<div className="App">
<img src={images[index]} alt="Current slide" /></div>
);
}
In this version, the prev function is omitted. Instead, we employ the useEffect hook to set up an interval that automatically calls next every second. We ensure to clear the timer when the component unmounts.
Conclusion
Creating an image slider with React and JavaScript is straightforward, allowing for both manual and automatic transitions between images. For further information, visit plainenglish.io.
Explore how to build a React image slider from scratch with this tutorial.
A beginner's guide to creating an image carousel/slider with React.