• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

208
Views
React image slider with dynamic data, first Image coming after clickEvent

I've built a grid of images coming from an API, and now I am trying to build a slider. First image to be displayed should be the one clicked in the Grid below the slider , and when clicked next/prev go to the nex/prev img in the array.

How could I get it?

I am trying by setting the initial state of ``ìmgToShow```to the img clicked, but i get nothing in console. The idea would be to get that, and then , i still dont know how, update the state to show the next img in the Array.

album is the array of objects with all the images. Fetched in my Context component clickedImagecontains the clicked image's URL. I get it from a click event in other component.

This is my component :

import React, { useContext, useState } from "react";
import { AlbumContext } from "../../context/AlbumContext";
import "./carousel.css";
import BtnSlider from "./BtnSlider";

function Carousel() {
  const { clickedImage, albums } = useContext(AlbumContext);

  const [imgToShow, setImgToShow] = useState(clickedImage);
    console.log("imgTOSHOW", imgToShow); // empty in console
    console.log("clickedIMG in context", clickedImage); // gives me the URL clicked

  
  const [slideIndex, setSlideIndex] = useState(1);

  const nextSlide = () => {
    if (slideIndex !== albums.length) {
      setSlideIndex(slideIndex + 1);
    } else if (slideIndex === albums.length) {
      setSlideIndex(1);
    }
  };

  const prevSlide = () => {};

  return (
    <div className="container-slider">
      {albums &&
        albums.map((item, index) => {
          return (
            <div
              key={item.id}
              className={
                slideIndex === index + 1 ? "slide active-anim" : "slide"
              }
            >
              
              <img src={imgToShow} alt="" />
            </div>
          );
        })}
      <BtnSlider moveSlide={nextSlide} direction={"next"} />
      <BtnSlider moveSlide={prevSlide} direction={"prev"} />
    </div>

  );
}

export default Carousel
almost 3 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error