3

From the doc :

enter image description here

This is a simple ES6 arrow function, but I can't find the benefits of wraping the ( onClick, completed, text ) params with brackets ( aka : ({ onClick, completed, text }) ) - no doc mention - no examples

const Todo = ({ onClick, completed, text }) => ( <---- here
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
  >
    {text}
  </li>
)

export default Todo

I guess this looks like when we do import :

import  { PropTypes, Component } from 'react'

Cheers

Marwen Trabelsi
  • 3,951
  • 7
  • 37
  • 71

1 Answers1

4

This is called object destructuring.

You are looking at a react code, in which props is an object:

const props = { onClick: function() {}, completed: false, text: 'some string' };

To use the props object properties directly, we use destructuring to assign them to separate variables:

const Todo = ({ onClick, completed, text }) => ( <---- here
  <li
    onClick={onClick} // <-- the onClick variable
    style={{
      textDecoration: completed ? 'line-through' : 'none'  // <-- the completed variable
    }}
  >
    {text}  // <-- the text variable
  </li>
)

If we didn't use destructuring, we'll have to get the properties from the props object using the dot notation:

const Todo = (props) => ( <---- here
  <li
    onClick={props.onClick} // <-- the onClick property
    style={{
      textDecoration: props.completed ? 'line-through' : 'none'  // <-- the completed property
    }}
  >
    {props.text}  // <-- the text property
  </li>
)

Destructuring and Import have a very close syntax, but their not the doing exactly the same thing - you can read more about it in this answer.

Community
  • 1
  • 1
Ori Drori
  • 145,770
  • 24
  • 170
  • 162