Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!