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

click an image and add class to it but when selectin other one remove the class

I have multiple images which I can select from a carousell. These images are rendered from a map function like this:

 {imagenesProductos.map((img) => {
                  if (img) {
                    console.log(img);
                    return (
                      <SwiperSlide className="">
                        <Image onClick={e => clickedImage(e)} className="product" src={img} width={100} height={100} alt='productImage' />
                      </SwiperSlide>
                    )
                  }
  })}
              

When I click the image I have a method that just console logs the src of the image.

  const clickedImage = (e) => {
    console.log(e.target.src)
  }

What I want to do is to add a class to the selected image and remove it when I select another one. I am using styled components.

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 hope you can help me! Thanks in advance.

>Solution :

You should have a state that holder an identifier of this specific selected image. For example:

const [selectedPath,setSelectedPath]=useState('');

Than, in the map you can add a condition with this state, and use the className where you need.

 {imagenesProductos.map((img) => {
                  if (img) {
                    console.log(img);
                    return (
                      <SwiperSlide className="">
                        <Image onClick={clickedImage} className=`product ${img===selectedPath?"selected":""}` src={img} width={100} height={100} alt='productImage' />
                      </SwiperSlide>
                    )
                  }
  })}

And the clickImage function should be:

 const clickedImage = (e) => {
    console.log(e.target.src);
    setSelectedPath(e.target.src);
  }
           
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