4

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

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.