Monica White
Monica White

Reputation: 61

A javascript reactjs question about props

Here is the simple App.js code:

import React from 'react'
import Member from './Member'

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]
  for (const member of members) {
    return <Member {...member} />
  }
}

export default App

Here is the Member.js:

import React from 'react'

function Member ({ name, age }) {
  return (
  <div>
    {name}
    <hr />
    {age}
  </div>)
}

export default Member

The problem is only the first object {name:'Andy', age: 22} shows in the browser. How can I change the code to show all three of them? I am new to Javascript and React. I just can't figure it out. Can anyone help? Thanks a lot.

Upvotes: 0

Views: 76

Answers (4)

Billy Brown
Billy Brown

Reputation: 2342

As soon as you call return, it will exit the function and return the result of the expression beside the return keyword. Even though you are returning within a for loop, your code will return the value immediately from the function.

If instead you want to return an array of items, you can use map, like this:

function App () {
  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ];
  return {members.map((member, index) => <Member key={index} {...member} />)};
}

map allows you to execute a function over every element in an array, and then return that modified array. When creating a collection of elements, they each need a unique (unique to the collection) key attribute. I am using the index of the item in the array here.

Upvotes: 0

Ayudh
Ayudh

Reputation: 1763

Please bear in mind that the other answers use member name as the key which is poor practice. Imagine if you had two members with the same name, then you'd get the duplicate key error.

Try:

import React from 'react'
import Member from './Member'


function App () {

  const members = [
    { name: 'Andy', age: 22 },
    { name: 'Bruce', age: 33 },
    { name: 'Mary', age: 11 }
  ]

  return  (
    members.map((member, index) => (
      <Member key={`${member.name}${index}`} {...member} />
    ))
  )
}

export default App

Upvotes: 0

iClass Chima
iClass Chima

Reputation: 366

One way is not to spread the props at first

Pass the array as it is as

Then in the Member component; use the .map() function to iterate over the Member props like member.map(user => {user.name}, {user.age} )

Hope that helps

Upvotes: 0

Yash Joshi
Yash Joshi

Reputation: 2774

This is happening because as soon as the first iteration is initiated you are returning the jsx and thus it shows only the first member.

Here how you can loop on all members

return (
  <React.Fragment>
    {members.map(member => <Member key={member.name} {...member} /> )}
  </React.Fragment>
)

Upvotes: 2

Related Questions