Introduction
In this article, I'm going to show how to create custom React components for an image slider that will fetch the data from the API and load it in our React application.
Requirement
- Basic knowledge of React
- Knowledge about useState & useEffect hooks
- Visual Studio Code
Step 1. We need to create a new React app using the below command.
npx create-react-app image-slider
Open the folder in the VS Code and then open the command prompt to install the React icons page.
npm install react-icons
Step 2. Create a new folder named components and then a new file named ImageSlider.js and add the following code.
import { useEffect, useState } from "react";
import { BsArrowLeftCircleFill, BsArrowRightCircleFill } from "react-icons/bs";
import "./styles.css";
function ImageSlider({ url, page = 1, limit = 5 }) {
const [photos, setPhotos] = useState([]);
const [currentSlide, setCurrentSlide] = useState(0);
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
async function fetchPhotos(getUrl) {
try {
setLoading(true);
const response = await fetch(`${getUrl}?page=${page}&limit=${limit}`);
const data = await response.json();
if (data) {
setPhotos(data);
setLoading(false);
}
} catch (e) {
setErrorMessage(e.message);
setLoading(false);
}
}
useEffect(() => {
if (url !== "") {
fetchPhotos(url);
}
}, [url]);
function handlePrevious() {
setCurrentSlide(currentSlide === 0 ? photos.length - 1 : currentSlide - 1);
}
function handleNext() {
setCurrentSlide(currentSlide === photos.length - 1 ? 0 : currentSlide + 1);
}
console.log(photos);
if (loading) {
return <div>Loading...</div>;
}
if (errorMessage !== null) {
return <div>Error Occured !{errorMessage}</div>;
}
return (
<div className="container">
<BsArrowLeftCircleFill onClick={handlePrevious} className="arrow left-arrow" />
{photos && photos.length
? photos.map((imageItem, index) => (
<img
src={imageItem.download_url}
alt={imageItem.author}
key={imageItem.id}
className={
currentSlide === index
? "current-image"
: "current-image hide-current-image"
}
/>
))
: null}
<BsArrowRightCircleFill onClick={handleNext} className="arrow right-arrow" />
<span className="circle-indicators">
{photos && photos.length
? photos.map((_, index) => (
<button
key={index}
className={
currentSlide === index
? "current-indicator"
: "current-indicator inactive-indicator"
}
onClick={() => setCurrentSlide(index)}
></button>
))
: null}
</span>
</div>
);
}
export default ImageSlider;


Join the conversation! Your thoughts help the community grow.