Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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.

I hope you can help me! Thanks in advance.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use a state to track clicked images. if the current image in the map is a selected image then you can add a class active or anything you like. I am using index as key as list of image wouldn’t change often I suppose. Following is the sample code for it.

const [curImageIndex, setCurImageIndex] = useState(null);
  const clickedImage = (index) => {
    setCurImageIndex(index);
  };

  return (
    <>
      {magenesProductos.map((img, index) => {
        if (img) {
          console.log(img);
          return (
            <SwiperSlide
              className={`product ${curImageIndex === index? 'active' : ''}`}
              key={index}
            >
              <Image
                onClick={() => clickedImage(index)}
                className="product"
                src={img}
                width={100}
                height={100}
                alt="productImage"
              />
            </SwiperSlide>
          );
        }
      })}
    </>
  ); 
about 4 years ago · Juan Pablo Isaza Relatório

0

Use a single state to hold the currently selected image. Filter imagenesProductos before mapping. Compare the currently mapped img to the stored selectedImage state to conditionally add the other class to the image.

const [selectedImage, setSelectedImage] = React.useState(null);

...

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

...

{imagenesProductos
  .filter(img => img)
  .map((img) => {
    console.log(img);
    return (
      <SwiperSlide className="">
        <Image
          onClick={clickedImage}
          className={["product", selectedImage === img ? "newClass" : ""].join(" ")}
          src={img}
          width={100}
          height={100}
          alt='productImage'
        />
      </SwiperSlide>
    );
  }
})}
about 4 years ago · Juan Pablo Isaza Relatório

0

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);
  }
           
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda