Evanss
Evanss

Reputation: 23173

Loop through array and render multiple instances of a child component with that data with React?

I have a parent component called ListContainer which contains a child component called ListItem. I need ListItem to be called for every item in an array called nameArray, and for the ListItem's name to be populated from the values in this array.

export const ListItem = (props) => {
  return <h2>Name: { props.name }</h2>;
};

export const ListContainer = (props) => {
  const nameArray = [
    {
      name: "john",
      age: "29"
    },
    {
      name: "james",
      age: "21"
    }
  ];
  return (
      <div>
      { this.nameArray.map(function(item) {
          return (
            <ListItem name={ item.name } />
          )
      }) }
      </div>
    );
};

From looking at the docs I think I need to use the map function, but im confused as to how it works in JSX.

https://facebook.github.io/react/docs/lists-and-keys.html

Upvotes: 4

Views: 4879

Answers (1)

John Ruddell
John Ruddell

Reputation: 25862

You are trying to reference a local variable created in the render function, so remove the this from this.nameArray.map

{ nameArray.map( (item, i) => <ListItem key={i} name={ item.name } /> )}

Also your react component here is an inline stateless component. Its just a regular function with no react this context. aka you dont have this.props or this.state. you just have props. When you want to access props you only type props instead of this.props

Upvotes: 8

Related Questions