Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional React Component with an argument in curly braces

This is called a "destructuring". Actually, you're passing an object as an argument to the function, but the destructuring uses only the named properties of the object.

const destructuring = ({ used }) => console.log(used);
    
const properties = {
  unused: 1,
  used: 2,
};

destructuring(properties); // 2

You can even use it for creating variables.

const properties = {
  name: 'John Doe',
  age: 21,
};

const { name, age } = properties;

console.log(name, age); // John Doe 21

I'm a newbie to React, but I think yes, items is a prop, and passing {items} as an argument destructures the props object, and thus the function uses only the prop items, in order to simplify the code. This way you can use items in the functional component, instead of props.items. For example, I tested a similar situation in the following code. Using destructuring looks like this:

const ListItem = ({content}) => (
  <li>{content}</li>
);
...
<ListItem key={index} content={content} />

Whereas if you used props it would look like this:

const ListItem = (props) => (
  <li>{props.content}</li>
);
...
<ListItem key={index} content={content} />

So for your example, using props would look like this:

const List = (props) => (
  <ul className="list">
    {props.items.map(item => <ListItem item={item} />)}
  </ul>
);

Meanwhile, destructuring allows you to simplify to items, rather than props.items which is what was being done in your original code:

const List = ({ items }) => (
  <ul className="list">
    {items.map(item => <ListItem item={item} />)}
  </ul>
);

Cheers! --Omar