0

I need to return the following code in ReactJS x amount of times. I am trying to populate a card with names based on how many people there are in a team.

So if x was 5, I would need that to appear 5 times.

<div className="row align-items-center justify-content-center m-b-10">
   <h5>Name goes here</h5>
</div>

This is the type of object I'm dealing with:

enter image description here

Is there a clean way of doing this?

legit98
  • 57
  • 1
  • 7
  • Does this answer your question? [Most efficient way of rendering JSX elements when iterating on array of data in React](https://stackoverflow.com/questions/52176673/most-efficient-way-of-rendering-jsx-elements-when-iterating-on-array-of-data-in) – Rodentman87 Jun 21 '20 at 23:50

3 Answers3

0

Assuming you got all of the people names in an array. You can use map over the array when rendering`:

{ yourObject.map((person, idx)=>(
    <div className="row align-items-center justify-content-center m-b-10" key={idx}>
         <h5>{person.first_name + " " + person.last_name}</h5>
     </div>
)}

(Of course, make sure this code is wrapped with another element)

Stan Loona
  • 615
  • 9
  • 18
SomoKRoceS
  • 2,934
  • 2
  • 19
  • 30
  • I'm working with an object. I attached a picture on my original post. I was able to solve the problem by using an arrow and pushing the
    to it each time, however, it's messy. I don't believe you can map over an object the way you have it, right?
    – legit98 Jun 22 '20 at 00:03
  • @legit98 your object is an array. So it should work. Look at my edit :) – SomoKRoceS Jun 22 '20 at 00:06
0

First, it depends on how your data is defined, for example, if the names are in an array, you can create an array of JSX elements that contain each , you can use .map()

0

Just use:

const x = 5
Array(x).fill().map((el, index) => 
    <div className="row align-items-center justify-content-center m-b-10" key={index}>
         <h5>Name here</h5>
     </div>
)

This is not ideal because you can also iterate over the array of names itself, and get the same result, even cleaner.

<div>
    {
        arrayOfNames.map((el, index) => (
            <div className="row align-items-center justify-content-center m-b-10" key={index}>
                 <h5>`${el.first_name} ${el.last_name}`</h5>
             </div>
        ))
    }
</div>
CevaComic
  • 2,056
  • 2
  • 6
  • 12