How to create an image slider component in react

How to create an image slider component in react 

how to create image-slider component in react

jsx code for image slider component in react

import React, { useState } from 'react';

const ImageSlider = ({ images }) => {

const [currentImageIndex, setCurrentImageIndex] = useState(0);

const previousImage = () => {

const newIndex = currentImageIndex === 0 ? images.length - 1 : currentImageIndex - 1;



const nextImage = () => {

const newIndex = currentImageIndex === images.length - 1 ? 0: currentImageIndex + 1;



return (

<div className="image-slider">

<button onClick={previousImage}>Previous</button>

<img src={images[currentImageIndex]} alt={`Image ${currentImageIndex + 1}`} />

<button onClick={nextImage}>Next</button>




export default ImageSlider;

In this code, the ImageSlider component receives an array of images as a prop. It uses the 'useState' hook to keep track of the current image index. The 'previousImage' and 'nextImage' functions update the current image index based on the button clicks. The render method displays the previous button, the current image, and the next button. Each button has an onClick event handler that triggers the corresponding function.

You can use this component in your application by importing and rendering it like any other React component. For example:

import React from 'react';
import ImageSlider from './ImageSlider';

const App = () => {
  const images = [
    // Add more image URLs here

  return (
      <h1>Image Slider Example</h1>
      <ImageSlider images={images} />

export default App;

Make sure to replace the image URLs in the images array with the actual URLs or file paths of your images.


Post a Comment

* Please Don't Spam Here. All the Comments are Reviewed by Admin.