Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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

like image 327
Evanss Avatar asked Mar 10 '23 07:03

Evanss


1 Answers

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

like image 72
John Ruddell Avatar answered May 19 '23 03:05

John Ruddell