Steve
Steve

Reputation: 596

Looping through multiple items and rendering each

I'm having issues with wrapping my head around React to loop through things to render a component multiple times in a row. Here's what I've got but it's not working. Some pointers as to what I'm doing wrong and a better way of doing it would be appreciated, thanks!

const users = [
    {
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }, {
        "firstName": "Peter",
        "lastName": "Jones"
    }
];

function Welcome(props) {
  return <h1>Hello, {props.firstName} {props.lastName}</h1>;
}

function allUsers(){
    return (
        <div>
            {for(var i=0; i<users.length; i++){
                <Welcome firstName={users[i].firstName} lastName={users[i].lastName}/>
            }}
        </div>
    )
}

ReactDOM.render(
  allUsers(),
  document.getElementById('root')
);

Upvotes: 0

Views: 48

Answers (2)

P. Zietal
P. Zietal

Reputation: 324

Also since it's not big wall of code and you are using ES6 I allowed myself to rewrite entire code to show you "a better way of doing it".

const users = [
    {
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }, {
        "firstName": "Peter",
        "lastName": "Jones"
    }
];

const Welcome = ({firstName, lastName}) => <h1>Hello, {firstName} {lastName}</h1>;

const AllUsers = () => (
        <div>
          {
            users.map((user, key) => <Welcome key={key} firstName={user.firstName} lastName={user.lastName} />)
          }
        </div>
)

ReactDOM.render(
  <AllUsers />,
  document.getElementById('root')
);

Upvotes: 1

Fabian Schultz
Fabian Schultz

Reputation: 18556

Try using .map instead of the for loop. It's usually easier to use in React:

const users = [
    {
        "firstName": "John",
        "lastName": "Doe"
    }, {
        "firstName": "Anna",
        "lastName": "Smith"
    }, {
        "firstName": "Peter",
        "lastName": "Jones"
    }
];

function Welcome(props) {
  return <h1>Hello, {props.firstName} {props.lastName}</h1>;
}

function allUsers(){
    return (
        <div>
            {users.map(function(user) {
                return <Welcome key={user.firstName} firstName={user.firstName} lastName={user.lastName}/>
            })}
        </div>
    )
}

ReactDOM.render(
  allUsers(),
  document.getElementById('View')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>

Upvotes: 2

Related Questions