ReactJS Slider to make dynamic slider component by fetching data from API

ReactJS Slider to make dynamic slider component by fetching data from API

Here, I am going to explain the dynamic slider component in React that fetches data from an API. I'll use the JSONPlaceholder API to simulate fetching dynamic data.

import React, { useState, useEffect } from 'react';

const Slider = () => {
  const [sliderData, setSliderData] = useState([]);
  const [currentSlide, setCurrentSlide] = useState(0);

  useEffect(() => {
    // Fetch data from an API (using JSONPlaceholder as an example)
    const fetchData = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/photos?_limit=5');
        const data = await response.json();
        setSliderData(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []); // Run once when the component mounts

  const handleNextSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide + 1) % sliderData.length);
  };

  const handlePrevSlide = () => {
    setCurrentSlide((prevSlide) => (prevSlide - 1 + sliderData.length) % sliderData.length);
  };

  return (
    <div>
      {sliderData.length === 0 ? (
        <p>Loading...</p>
      ) : (
        <div>
          <button onClick={handlePrevSlide}>Previous</button>
          <img
            src={sliderData[currentSlide].url}
            alt={sliderData[currentSlide].title}
            style={{ maxWidth: '100%', maxHeight: '300px' }}
          />
          <button onClick={handleNextSlide}>Next</button>
        </div>
      )}
    </div>
  );
};

// Example usage
const App = () => {
  return (
    <div>
      <h1>Dynamic Slider Component with API Data</h1>
      <Slider />
    </div>
  );
};

export default App;

In this example,

  • In this example,

    • We get data from the JSONPlaceholder API when the component loads using useEffect.

    • The sliderData state keeps the data from the API.

    • The current slide state shows the index of the slide being displayed.

    • The handleNextSlide and handlePrevSlide functions change the current slide as needed.

    • The slider shows an image from the data with "Next" and "Previous" buttons.

Don't forget to change the API endpoint and data structure to match your real API details. You can also change the slider's look and transitions to fit your project's needs.