search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Problem analysis: Why is the last picture always displayed?
Solution: Accurately pass data through Props
Step 1: Modify the parent component MyPhotos and pass the image source through Props
Step 2: Modify the sub-component PageComponent to receive and display Props
Step 3: Handle dynamic updates (optional, but recommended)
Summary and best practices
Home Web Front-end JS Tutorial Image display problem between React components: precise data transfer and dynamic update through Props

Image display problem between React components: precise data transfer and dynamic update through Props

Nov 28, 2025 pm 12:21 PM

Image display problem between React components: precise data transfer and dynamic update through Props

This article aims to solve the problem in React applications that after clicking a picture in the picture list, the corresponding picture cannot be displayed correctly in the new page or modal box, and the picture at the end of the list is always displayed. The core solution is to use React's props mechanism to pass the clicked image data to the target component as an attribute, and combine useState and useEffect to implement dynamic updates to ensure that the user interface always displays the correct content.

When building React applications, we often need to display a list of data, such as an image gallery. When the user clicks on an element in the list, we may want to display the details of that element in a separate component (such as a modal or a new page). However, a common pitfall is that if the data is passed incorrectly, the target component may not correctly identify which element the user clicked on, resulting in display errors.

Problem analysis: Why is the last picture always displayed?

In the original code provided, the problem lies in how the clicked image information is passed to the PageComponent. The original implementation is as follows:

 // MyPhotos.jsx (original question code snippet)
export default function MyPhotos() {
  const [isOpen, setIsOpen] = useState(false);

  const openNewPage = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div>
      {contents.map((content) =&gt; {
        return (
          <div key="{content.id}">
            <img  onclick="{openNewPage}" src="%7Bcontent.image%7D" alt="Image display problem between React components: precise data transfer and dynamic update through Props" >
            <pagecomponent isopen="{isOpen}" onclose="{openNewPage}">
                <img  onclick="{openNewPage}" src="%7Bcontent.image%7D" the problem: content.image here always points to last element of map loop alt="Image display problem between React components: precise data transfer and dynamic update through Props" >
            </pagecomponent>
          </div>
        );
      })}
    </div>
  );
}

The problem here is that PageComponent is a subcomponent, and although its internal Image display problem between React components: precise data transfer and dynamic update through Props tag is written in the map loop, in fact when the isOpen state becomes true, React will render Image display problem between React components: precise data transfer and dynamic update through Props in all PageComponent instances based on the value of content.image in the last iteration of the map loop. This means that no matter which image is clicked, all PageComponents will try to display the same (i.e. the one at the end of the list) image. In addition, the Image display problem between React components: precise data transfer and dynamic update through Props tag is passed in as the children of the PageComponent, but the children are not explicitly rendered internally in the PageComponent, which also leads to confusion in the data flow.

Solution: Accurately pass data through Props

The key to solving this problem is that when the user clicks on a specific image, we need to accurately pass the unique identifier of the image or its src attribute to the PageComponent. React's props (property) mechanism was born for this.

Step 1: Modify the parent component MyPhotos and pass the image source through Props

We no longer use the Image display problem between React components: precise data transfer and dynamic update through Props tag as a child element of PageComponent, but pass the image src to be displayed as a property (prop) of PageComponent. At the same time, in order to ensure that the click event can pass the correct picture information, we need to receive the currently clicked picture information in the openNewPage function or pass it when calling openNewPage.

 // MyPhotos.jsx (after modification)
import React, { useState } from 'react';
import PageComponent from './PageComponent'; // Assume PageComponent is at the same level or specified path // Simulate data structure const contents = [
  { id: 0, image: 'https://via.placeholder.com/150/FF0000?text=Img0', text: 'ABC' },
  { id: 1, image: 'https://via.placeholder.com/150/00FF00?text=Img1', text: 'ABCD' },
  { id: 2, image: 'https://via.placeholder.com/150/0000FF?text=Img2', text: 'ABCDE' }
];

export default function MyPhotos() {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedImageSrc, setImage display problem between React components: precise data transfer and dynamic update through PropsImageSrc] = useState(''); // Add a new state to store the src of the clicked image

  // Modify the openNewPage function to receive the image src as parameter const handleImageClick = (imageSrc) =&gt; {
    setImage display problem between React components: precise data transfer and dynamic update through PropsImageSrc(imageSrc); // Update the src of the clicked image
    setIsOpen(true); //Open modal box/new page};

  const closeNewPage = () =&gt; {
    setIsOpen(false);
    setImage display problem between React components: precise data transfer and dynamic update through PropsImageSrc(''); // Clear selection when closing};

  return (
    <div>
      {contents.map((content) =&gt; (
        <div key="{content.id}" style="{{" display: margin:>
          <img  onclick="{()" alt="Image display problem between React components: precise data transfer and dynamic update through Props" > handleImageClick(content.image)} // Pass the src of the current image when clicked
            src={content.image}
            alt={`Image ${content.id}`}
            style={{ width: '100px', height: '100px', cursor: 'pointer' }}
          /&gt;
          {/* PageComponent should only be rendered once and displayed when isOpen, instead of rendering each time in the map loop*/}
          {/* The rendering method here is wrong and will result in multiple PageComponent instances.
              The correct approach is: PageComponent only appears once in the return of the MyPhotos component.
              Or as a routing page rendered based on URL parameters.
              But in order to demonstrate data transfer, we temporarily keep it in the outer layer of the map.
              If the PageComponent is a modal, it should only be rendered once on top of the MyPhotos component.
          */}
        </div>
      ))}

      {/* Assuming that PageComponent is a modal box, it should be rendered once on top of the parent component*/}
      <pagecomponent isopen="{isOpen}" onclose="{closeNewPage}" imgsrc="{selectedImageSrc}" pass the clicked image src as prop></pagecomponent>
    </div>
  );
}

Important note: In the above modification, when PageComponent is used as a modal box, it should be rendered only once in the return statement of the MyPhotos component, instead of rendering a PageComponent instance for each image inside the map loop. PageComponent inside a map loop results in multiple instances, which is generally not the desired behavior of a modal box. The above code has moved the PageComponent outside the map loop to conform to the common usage pattern of modal boxes.

Step 2: Modify the sub-component PageComponent to receive and display Props

PageComponent now needs to receive the imgSrc prop and use it to set the src attribute of the inner Image display problem between React components: precise data transfer and dynamic update through Props tag.

 // PageComponent.jsx (after modification)
import React, { useState, useEffect } from 'react';

export default function PageComponent({ isOpen, onClose, imgSrc }) {
  // Modal box style (simplified example)
  const modalStyle = {
    display: isOpen ? 'block' : 'none', // Control display/hide position: 'fixed',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0,0,0,0.5)',
    zIndex: 1000,
    justifyContent: 'center',
    alignItems: 'center',
    padding: '20px',
    boxSizing: 'border-box'
  };

  const modalContentStyle = {
    backgroundColor: '#fff',
    padding: '20px',
    borderRadius: '8px',
    maxWidth: '80%',
    maxHeight: '80%',
    overflow: 'auto',
    position: 'relative',
    textAlign: 'center'
  };

  const closeButtonStyle = {
    position: 'absolute',
    top: '10px',
    right: '10px',
    cursor: 'pointer',
    fontSize: '24px',
    fontWeight: 'bold',
    color: '#333'
  };

  if (!isOpen) {
    return null; // If not opened, nothing will be rendered}

  return (
    <div style="{modalStyle}">
      <div style="{modalContentStyle}">
        <span style="{closeButtonStyle}" onclick="{onClose}">×</span>
        <h2>Image details</h2>
        {imgSrc ? (
          <img src="%7BimgSrc%7D" use imgsrc received from props alt="Image display problem between React components: precise data transfer and dynamic update through Props"   style="max-width:90%" maxwidth: maxheight: adjust the image size to fit modal box>
        ) : (
          <p>No picture selected</p>
        )}
      </div>
    </div>
  );
}

In this way, PageComponent no longer relies on the map loop context of the parent component, but explicitly receives the image source it needs to display.

In some cases, PageComponent may need to perform some side effects based on changes in imgSrc, or it may need to maintain a local state based on imgSrc internally. At this time, the useEffect hook comes in handy.

 // PageComponent.jsx (use useState and useEffect to handle dynamic updates)
import React, { useState, useEffect } from 'react';

export default function PageComponent({ isOpen, onClose, imgSrc }) {
  const [currentImageSrc, setCurrentImageSrc] = useState(""); // Internal state to manage image src

  useEffect(() =&gt; {
    //When the imgSrc prop changes, update the internal state setCurrentImageSrc(imgSrc);
  }, [imgSrc]); // The dependency array contains imgSrc to ensure that the effect is re-run when imgSrc changes // ... The modal box style code remains unchanged...

  if (!isOpen) {
    return null;
  }

  return (
    <div style="{modalStyle}">
      <div style="{modalContentStyle}">
        <span style="{closeButtonStyle}" onclick="{onClose}">×</span>
        <h2>Image details</h2>
        {currentImageSrc? ( // Use internal state currentImageSrc
          <img src="%7BcurrentImageSrc%7D" alt="Image display problem between React components: precise data transfer and dynamic update through Props"   style="max-width:90%" maxwidth: maxheight:>
        ) : (
          <p>No picture selected</p>
        )}
      </div>
    </div>
  );
}

The advantage of using useState and useEffect is that PageComponent can better manage its own state. For example, if the imgSrc prop changes again after the PageComponent is opened (for example, switching images via the left and right arrows), useEffect will ensure that currentImageSrc is updated in time to display the correct image.

Summary and best practices

  1. Data flow principle: In React, data usually follows the one-way data flow principle, that is, flows from parent components to child components. Via props is the standard way to implement this principle.
  2. Avoid creating multiple modal boxes in a loop: If the PageComponent is a modal box or a component that requires global control, it should usually be rendered only once at the top level of the parent component and control its display content and state through props (such as isOpen and imgSrc).
  3. Pass exactly the data you need: Avoid passing the entire object unless the child component really needs all the data. Passing only the minimum data required for child component rendering improves component clarity and performance.
  4. Use useState and useEffect to manage internal state: When subcomponents need to perform internal state management or side effect operations based on props, useState and useEffect are powerful tools. useEffect's dependency array is crucial, it determines when the side effect is re-run.
  5. Component reusability: Passing data through props makes PageComponent more versatile and reusable. It is no longer coupled to a specific contents array, but can display any incoming image.

Following these principles, you can effectively solve the problem of data transmission and display between components in React applications, and build a robust and maintainable user interface.

The above is the detailed content of Image display problem between React components: precise data transfer and dynamic update through Props. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to display last visited city and country of user on website How to display last visited city and country of user on website Mar 13, 2026 am 03:51 AM

The geographical location is obtained through the front-end and combined with the back-end storage to realize the dynamic prompt function of "the last visit was from XX city, XX country". It requires the help of IP location service, server-side persistence and front-end display logic.

The correct way to use express-validator for strong password verification The correct way to use express-validator for strong password verification Mar 09, 2026 am 03:33 AM

This article describes how to correctly configure the isStrongPassword option when using the express-validator library for strong password validation. Highlights a known issue with schema validation mode and provides detailed steps and code examples for using chained validation as an alternative to ensure passwords meet custom strength requirements.

Tailwind CSS dynamic class name invalidation problem: principle and solution Tailwind CSS dynamic class name invalidation problem: principle and solution Mar 07, 2026 am 12:30 AM

This article delves into the reason why Tailwind CSS cannot recognize dynamically generated class names (such as bg-[${variable}]) in React applications, mainly due to its JIT compiler's reliance on complete class names. The tutorial provides two effective solutions: one is to predefine the complete Tailwind class name in a variable, and the other is to use React's inline styles for specific CSS properties to help developers overcome dynamic style challenges and maintain code maintainability.

How to combine multiple regular expressions into a replacement pattern that performs efficiently How to combine multiple regular expressions into a replacement pattern that performs efficiently Mar 13, 2026 am 12:03 AM

This article introduces how to safely combine multiple independent regular expressions (such as URL cleaning, specific pattern word filtering, special character deletion) into a single regular expression in JavaScript through logical or (|), and implement multiple rule cleaning in one replace() to avoid repeated string traversal.

How to uniformly sample a specified number of elements (such as 5) from an array How to uniformly sample a specified number of elements (such as 5) from an array Mar 13, 2026 am 02:42 AM

This article introduces an accurate and efficient algorithm for extracting a fixed number (such as 5) of elements that are as evenly distributed as possible from an array of any length, ensuring that the first and last elements must be selected, the middle elements are distributed proportionally, and the original order is maintained.

Complete tutorial on naturally sorting JavaScript arrays by numbers at the end of file names Complete tutorial on naturally sorting JavaScript arrays by numbers at the end of file names Mar 13, 2026 am 06:12 AM

This article explains in detail how to correctly numerically sort an array of file names containing increasing numeric suffixes, and solve the problem of 13810 < 13912 being misjudged as a larger problem caused by the default string sorting of Array.prototype.sort().

Multi-page layout management and routing practice in Vue single-page applications Multi-page layout management and routing practice in Vue single-page applications Mar 10, 2026 am 03:09 AM

Vue implements a true single-page application (SPA) through Vue Router. It can dynamically switch "pages" of different layouts without refreshing or switching HTML files. All views are rendered on demand within index.html, keeping the Vue instance unified, the state controllable, and the experience smooth.

A general implementation method for inserting elements in batches according to periodic positions in JavaScript A general implementation method for inserting elements in batches according to periodic positions in JavaScript Mar 09, 2026 am 12:03 AM

This article describes how to accurately insert new elements at specified offset positions (such as the 2nd and 9th positions) at a fixed period (such as every 10 elements) in a JavaScript array to avoid repeated insertions and support dynamic array lengths and custom insertion values.

Related articles