0

I am developing a react app with a firebase backend. I loop through firestore collection and display the images from that collection.

const getdata = Object.entries(mydata).map(pair => {
    const key = pair[0]
    const value = pair[1]
    return (
        <div className='image">
        <img src={value} id={key} onclick={showpop} />
        </div>
    )
}

When the image is clicked, it should show a pop up, and I am doing that like so:

function showpop(){
    var img = document.getElementById(//get value of the id here from the key);
    img.onclick = function(){
        //show popup here
    }
}

I have tried with getElementById(key), getElementById(props.key), but they all give me errors.

3
  • 3
    why did you add another onclick function in showpop() ? Commented Jan 17, 2021 at 11:51
  • When I dont add the onclick, I get an error from this line : myImg.src = this.src; saying src is not defined. Commented Jan 17, 2021 at 12:53
  • you can set the image src on showpop when you bind the onclick={()=>{showpop(value)}}, just like my answer Commented Jan 17, 2021 at 12:59

2 Answers 2

1

If you are using Reactjs, then this onclick event should be onClick

const getdata = Object.entries(mydata)
   .map(([key, value])=> (
      <div className='image">
        <img src={value} id={key} onClick={showpop} />
     </div>));

then:

function showpop(event){
   const {id} = event.target; //--> get the img id property
   const src =  event.target.getAttribute("src") //--> get the src attribute
   //--> show popup
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can get the value when binding the function

<div className='image'>
   <img src={value} id={key} onclick={()=>{showpop(pair)}} />
</div>


function showpop(pair){
   console.log(pair)
}

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.