0

I want to open a popup after click on each card and show information of that card on popup but I can not get key to know index to choose information to show

const childElements = this.state.images.map(function (item, i) {
     return (
        <div key={item.id} data-key={i}>
          
          <MediaCard
            poster={item.largeImageURL}
            id={item.id}
            views={item.views}
            key={item.id}
            data-key={i}
          />
          
        </div>
      );
    });

I have to define index array to choose the right object to show on popup

            <StackGrid
              onClick={this.openModal}
            >

              {childElements}

            </StackGrid>

            {this.state.visible ? (
              
              <Popup id={this.state.images['I want to know index after click each card to insert heare'].id} handler={this.handler} />
            ) : null}
3
  • Can you get onClick event from MediaCard? Commented Aug 4, 2020 at 3:21
  • yes I can push onClick (onClick={() => this.openModal()} ) in Mediacard but nothing happen Commented Aug 4, 2020 at 3:37
  • Why not storing that i on onClick event? You know, we get the index of object in map. Commented Aug 4, 2020 at 4:00

1 Answer 1

1

you don't need know the index, you can save all the image object in your state.

add in your MediaCard a onClick event where you send the item to your state.

import React, { useState} from "react";
import "./App.css";



const images = [
      {id: 1, src : "https://d1nhio0ox7pgb.cloudfront.net/_img/i_collection_png/256x256/plain/chess_piece_bishop.png", alt: "image 1"}, 
      {id: 1, src : "https://cdn.iconscout.com/icon/premium/png-256-thumb/bishop-black-games-battle-checkmate-chess-camel-figure-58246.png", alt: "image 2"}
    ]

export default function App() {
  const [image, setImage] = useState({});


  const ChildElements = ({images}) => images.map(function (item, i) {
    return (
       <div key={item.id} data-key={i}>       
         <img
           src={item.src}
           alt={item.alt}         
           key={item.id}
           width='45px'
           data-key={i}
           onClick={() => setImage(item)}
         />       
       </div>
     );
   });


 
  return (
    <div className="App">
      <ChildElements images={images} />

      <h1>Image Selected</h1>
     <img src={image.src} width='90px' alt={image.alt}/>

    </div>
  );
}


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.