Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I reference an image element in an IF statement?

I’ve created a music player component and I’m adding an onclick function that will update the current song when the image is clicked.

I’ve got everything working so far except for this onclick feature.

I can get it working with one song but I now want to add conditionals to make it work with all of the images. For some reason I can’t remember how to target the image tag to reference it in my IF statement. I know this is very basic stuff but hopefully someone can remind me how to do it!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve shortened the code to make it easier to read.

   function getSong() {

    let songFile = songs.map(song => song.songFile)
    
    // I want to know what to add inside the () to reference the images.

    if ('Reference to Rap img') {
        setSongClicked(songFile[0])

    } else if ('Reference to Rock img') {
      setSongClicked(songFile[1])

    } else if ('Reference to Trending img') {
      setSongClicked(songFile[2])

    } else if ('Reference to Jazz img') {
      setSongClicked(songFile[3])
    }
   }

  return (

    <div className="song-main-container">
        <div className="song-container">
            <img src={Rap} onClick={getSong} />
            <img src={Rock} onClick={getSong}/>
        </div>
        <div className="song-container">
            <img src={Trending} onClick={getSong} />
            <img src={Jazz} onClick={getSong}/>
        </div>
    </div>

  )
}

>Solution :

Instead of trying to reference the element, just pass a value to the function. What value do you want to pass?

The code appears to be using hard-coded array index values:

setSongClicked(songFile[0])

So you can pass those values. For example:

<img src={Rap} onClick={() => getSong(0)} />

Then in the click handler function, expect that value as an argument:

function getSong(index) {

Then you don’t need an if statement at all. Just update state with that value:

setSongClicked(songFile[index]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading