user8685433 user8685433 - 3 years ago 131
React JSX Question

Can't understand syntax of params

I cant understand params syntax. What does ({todo, destroyTodo}) actually mean in this case? Why can’t we just use "props" as param?

const TodoItem = ({todo, destroyTodo}) => {
return (
<div>
{todo.text}
<span onClick={destroyTodo}> x </span>
</div>
)
}

Answer Source

The code you have shown creates a new component using a javascript function. The {todo,destroyTodo} is a json object which is passed as props to the component and destructured into 2 variables called todo and destroyTodo. It is a shorthand for

const TodoItem = (props) => {
  const  {todo, destroyTodo} = props;
  return (
    <div>
      {todo.text}
      <span onClick={destroyTodo}> x </span>
    </div>
  )
}

The same component created as a class would be

class TodoItem extends React.Component{

render(){
   return (
    <div>
      {this.props.todo.text}
      <span onClick={this.props.destroyTodo}> x </span>
    </div>
  )
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download