jbuddy_13
jbuddy_13

Reputation: 1276

React list and keys, missing object properties

In this react tutorial, the author uses a snippet of code, starting on line 61:

const List = (props) => (
  <ul>
    {props.list.map((item) => (
      <Item key={item.objectID} item={item} />
    ))}
  </ul>
);

This function is called from within the const, App, <List list={stories} /> on line 35. And lastly, stories is an object:

const stories = [
    {
      title: 'React',
      url: 'https://reactjs.org/',
      author: 'Jordan Walke',
      num_comments: 3,
      points: 4,
      objectID: 0,
    },
    {
      title: 'Redux',
      url: 'https://redux.js.org/',
      author: 'Dan Abramov, Andrew Clark',
      num_comments: 2,
      points: 5,
      objectID: 1,
    },
  ];

I'm confused regarding line 61, specifically the code props.list.map. From the object, stories, there is no list attribute. However, in line 35, <List list={stories} /> seems to imply that stories will be referenced by the key, list.

My questions are:

  1. What's going on here?
  2. Why would this extra complexity be beneficial (globally speaking beyond the context of this code)?

Upvotes: 0

Views: 321

Answers (2)

tenshi
tenshi

Reputation: 26354

Given any <Component prop={value} />, you access value with prop:

function Component(props) {
    props.prop; // get value :O
}

Many people use destructuring because it is easier to read:

function Component({ prop }) {
    prop; // get value too :O
}

And also if you have an object of props for a component, you can spread them:

const theProps = { prop: 42 };

return <Component {...theProps} /> // same as <Component prop={theProps.prop} />

Furthermore, you don't have to destructure every prop, you can collect the rest into an object to be used normally:

function Component({ importantProp, ...notAsImportant }) {
    importantProp; // easy access and to use

    notAsImportant.prop; // you can still get the other props normally
}

Upvotes: 1

Brian Thompson
Brian Thompson

Reputation: 14385

The prop is named list, but the value of that prop is being filled by the stories const. The reason you might do that is to make your List component generic and flexible.

If you wanted to reuse List for some other purpose, but had to pass it a prop named stories when you were actually passing it classes or some other type of list, it would be confusing.

In your case, just understand that props.list is actually stories here.

Upvotes: 2

Related Questions