Search code examples
reactjscomponents

What is meaning of ({}) while writing a function in reactjs


import React from 'react'
import PropTypes from 'prop-types'

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

Todo.propTypes = {
    onClick:PropTypes.func.isRequired,
    completed:PropTypes.bool.isRequired,
    text:PropTypes.string.isRequired
}

export default Todo

1)I have come across the code for Todo in OfficalDocumention

2) I was confused with const Todo = ( {onClick, completed, text} ) these part

3) Are we using destructing(es6 syntax) or we passing object type using json short Hand Syntax


Solution

  • A functional component is a function that receives one parameter: props. Since props is always an object, you can choose to destructure it's properties into their own variables using this syntax.

    This is not limited to functional components though. Consider the following function:

    cont myObj = {
      val: 'foo',
      other: 'bar'
    }
    
    function myFunction({ val, other }) => {
      return val + other;
    }
    
    myFunction(myObj); // foobar
    

    Its a way to more explicitly declare a function's parameter requirements when using an object as an argument, and it also assigns them to variables so that you don't have to reference each one as myObj.val or myObj.other.

    So the functional component equivalent would be:

    <MyComponent val="foo" other="bar" />
    
    // Underneath react still calls our functional component like this
    // where props is an object containing val and other
    MyComponent(props) 
    
    const MyComponent = ({val, other}) => {...}