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

132
Visualizações
Returning multiple elements based on an array with React

I'm trying to conditionally return different divs with this function (first time using React):

  currUser().played.forEach(square => {
    if (square === id) {
      console.log(0)
      return (
        <div className="inactive">
        </div>
      );
    };
  });
  return (
    <div className="square">
    </div>
  );
}

0 gets logged a few times, but all outputs are of class square. How do I fix this?

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

0

You should be using the map method in order to output an array of elements. Like so:

const Square = () => {

   //...

    return ( 
      <div> 
         currUser().played.map(square => {
           if (square === id) {
           console.log(0)
           return (
              <div className="inactive">
              </div>
             );
           };
           return (
              <div className="square">
              </div>
            );
         })
      </div>
    )

}

export default Square;
about 4 years ago · Juan Pablo Isaza Relatório

0

I'm not sure that if you also want to render the div with className="square", if YES then the correct way to do this should be like this:

return (
<>
 {currUser().played.filter(square => square === id)
   .map(square => (
      <div className="inactive">
      </div>
    )}
   <div className="square">
   </div>
</>
)

First, you have to filter out you required elements then chain it with map to return and render out the desired elements.

map can't be used with if condition because map should always return something in each iteration. And if you really want to use if condition map then you must also return something in else

Here curly braces are used to run javascript inside JSX.

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