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;

setCurrentImageIndex(newIndex);

};



const nextImage = () => {

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

setCurrentImageIndex(newIndex);

};




return (

<div className="image-slider">

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

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

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

</div>

);

};




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 = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    // Add more image URLs here
  ];

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

export default App;



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

Tags

Post a Comment

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