Possible issue with accurate indexing causing caption error with API images in React

Continuing from: Implementing a lightbox feature in react-multi-carousel for my ReactJS app

My application utilizes react-images for the lightbox functionality and react-carousel-images for the carousel. The API provides a title and image data. The issue I am encountering is that the title shown in the footer caption always reflects the selected image and does not update when navigating through the carousel in the lightbox mode. I suspect this may be related to the index of the selected image. Below is a link showcasing the problem:

CodeSandbox Example

slider.js

import React, { Component } from "react";
// import "../slider/slider.css";
import "./slider.css";
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
import LightBox, { Modal, ModalGateway } from "react-images";

const responsive = {
  superLargeDesktop: {
    breakpoint: { max: 4000, min: 3000 },
    items: 1
  },
  desktop: {
    breakpoint: { max: 3000, min: 1024 },
    items: 1
  },
  tablet: {
    breakpoint: { max: 1024, min: 464 },
    items: 1
  },
  mobile: {
    breakpoint: { max: 464, min: 0 },
    items: 1
  }
};

class Slider extends Component {
  _isMounted = false;

  state = {
    awsApiData: [],
    loading: false,
    //selectedIndex: 0,
    selectedImage: {},
    lightboxIsOpen: false
  };

  componentDidMount() {
    this._isMounted = true;
    console.log("App mounted");
    this.setState({ loading: true });
    
    fetch("https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/imgApi")
      .then(data => data.json())
      .then(data =>
        this.setState({
          awsApiData: data.map(item => ({
            ...item,
            source: item.image
          })),
          loading: false
        })
      );
  }
  componentWillUnmount() {
    this._isMounted = false;
  }

  toggleLightbox = (post, selectedIndex) => {
    this.setState(state => ({
      lightboxIsOpen: !state.lightboxIsOpen,
      selectedImage: { title: post.title, index: selectedIndex }
    }));
  };

  render() {
    return (
      <div>
        {this.state.loading ? (
          <div className="text-center">Loading...</div>
        ) : (
          <div>
            <Carousel
              additionalTransfrom={0}
              showDots={false}
              arrows={true}
              autoPlaySpeed={3000}
              autoPlay={true}
              centerMode={false}
              className="slider"
              containerClass="container-with-dots"
              dotListClass="dots"
              draggable
              focusOnSelect={false}
              infinite
              itemClass="carousel-top"
              keyBoardControl
              minimumTouchDrag={80}
              renderButtonGroupOutside={false}
              renderDotsOutside
              responsive={responsive}
            >
              {Object.values(this.state.awsApiData).map((post, indx) => {
                return (
                  <div
                    className="mt-5"
                    key={indx}
                    onClick={() => this.toggleLightbox(post, indx)}
                  >
                    <img
                      className="media-img card-img-top card-img-hero"
                      src={post.source}
                      alt="Alt text"
                      style={{ cursor: "pointer" }}
                    />
                  </div>
                );
              })}
            </Carousel>
            <ModalGateway>
              {this.state.lightboxIsOpen ? (
                <Modal onClose={this.toggleLightbox}>
                  <LightBox
                    components={{
                      FooterCaption: () => <div>{this.state.selectedImage.title}</div>
                    }}
                    currentIndex={this.state.selectedImage.index}
                    frameProps={{ autoSize: "height" }}
                    views={this.state.awsApiData}
                  />
                </Modal>
              ) : null}
            </ModalGateway>
          </div>
        )}
      </div>
    );
  }
}

export default Slider;

Answer №1

Make sure you update the caption for your image when the lightbox view changes by utilizing the onViewChange handler in the LightBox component:

<LightBox onViewChange={handleLightBoxViewChange} .../>

The handleLightBoxViewChange function should be implemented to update the selected image using setState:

handleLightBoxViewChange = (newIndex) => {
  this.setState(state => ({
    selectedImage: state.awsApiData[newIndex]
  }));
};

If updating the state is not desired, you can alternatively pass the current view to the footer component like this:

<LightBox
  components={{
    FooterCaption: ({currentView}) => <div>{currentView.title}</div>
  }}
  //...
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the height of a child tag: A step-by-step guide

When trying to set the height of a child tag to 100%, I encountered an issue where the height would remain fixed after redirecting to another page, preventing the page from scrolling. Styling for Image 1 body{ background: url("Resources/Cash.jpeg&q ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...

What could be the reason behind the index not getting properly set for the array that was cloned afterward?

I need assistance with a code snippet that clones an array, resets the index (0, 1, 2 ...), and stores it in a variable named buildingsPayload: console.log('1:', this.buildings) const buildingsPayload = this.buildings.map((building, index) => ...

Passing current data into a predefined function using useCallback in React

Currently, I'm using Next.js and React to develop an application where I am facing a challenge with opening a model using a function while passing data from the current state. I have been able to fetch updated data from my Supabase database successful ...

When utilizing Axios to communicate with a backend server, an error message of "The requested resource could not be found (404)" may be displayed

Currently, I am developing a Web Application using React. The application features a login/register function for user authentication. To achieve this, I have set up an express server to handle HTTP requests to interact with a MYSQL database. Two specific e ...

What steps should I take to design and implement this basic search form?

Essentially, I have a three-page setup: - One page containing all possible search results such as: 'search result 1' 'search result 2' 'search result 3' - Another page with a search form and enter button. - And finally, a res ...

jQuery Datatables have trouble accessing specific row information when the table is set to be responsive

Currently, I'm utilizing the jQuery DataTables plugin along with the responsive addon to dynamically display and hide columns based on the size of the browser window. One of the columns is labeled as Actions, which permits users to edit a record by c ...

Next/image is encountering an error due to an invalid Element type being generated

Trying to utilize the next/image feature to display an SVG image is causing me some trouble. Every time I attempt this, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Actions cannot be performed on elements generated by ng-repeat

I am facing a challenge where I need to display a list of languages on a page, allowing users to change their selections based on previous choices. To achieve this functionality, I have written the following code snippet: ... <tbody> & ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Regex pattern is malfunctioning

I am having trouble understanding why this regex keeps returning false. I have an onkeydown event that should trigger it when pressing the 'w' key, but it doesn't seem to be working. var keyGLOB = ''; function editProductSearch ( ...

What is the process for logging out when a different user signs in using Firebase authentication in a React Native application?

I am new to React Native and facing challenges with managing authentication state in my application. Currently, I am using Redux but have not yet implemented persistence for user login. I have incorporated Firebase authentication. Essentially, I would li ...

When attempting to activate my venv in Python, I encounter issues as the terminal notifies me that it does not recognize the term '.venvScriptsactivate' as a cmdlet

Currently working as a React JS developer, I recently encountered an issue while trying to run the backend part of my code. The backend developer advised me to download Python and execute certain commands in the Webstorm terminal. How to activate the virtu ...

I am having trouble running my project locally using npm start

Recently, I began working with ReactJS. However, I encountered an issue when trying to start the server using npm start. It seems that the start script is missing from package.json. I added the start script to the scripts section and attempted npm start, b ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

I'm curious about the potential vulnerabilities that could arise from using a Secret key as configuration in an express-session

Our code involves passing an object with a secret key's value directly in the following manner --> app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }) I am pondering wheth ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

Generate a list of items in typescript, and then import them into a react component dynamically

I have a variable that stores key/value pairs of names and components in a TypeScript file. // icons.tsx import { BirdIcon, CatIcon } from 'components/Icons'; interface IconMap { [key: string]: string | undefined; } export const Icons: IconM ...

What steps can I take to limit access to my API exclusively for the Frontend?

I'm in the process of creating a gaming platform, and unfortunately, there has been an exploitation of the API. How can I establish a set of "approved domains" that are allowed to access my API? The previous misuse of the API resulted in individuals ...