Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of destructuring props in react

I have seen two ways to destructure props in React.

    function MyComponent({name,age,height}){
            // do stuff here
    }

or

    function MyComponent(props){
            const {name,age,height} = props
            // do stuff here
    }

Suppose this component is used as

<MyComponent name="bob" age={25} height = {175} haspets={false}/>

Here is my questions:

If I used the first way of destructuring, does it mean that I will have no access to other pros, in this case haspets

What are some pros/cons of these two ways?

like image 741
Phantom Avatar asked Jan 04 '20 00:01

Phantom


1 Answers

You can have access on the other properties of your object later, throught the arguments object, though as also pointed out on the link the rest parameters should be prefered.

<MyComponent name="bob" age={25} height = {175} surname="test" haspets={false} />

function MyComponent({ name, age, height, ...rest }){
      // rest will be an object like { surname: 'test', haspets: false }
}

One of the differences I can think of, and I suppose the most important, is that on the second case, while you are destructing your props object, you are using const on declaration.

In that way, you can no longer change these values on your MyComponent, while on your first case you could easily modify them.

like image 128
Michalis Garganourakis Avatar answered Sep 22 '22 01:09

Michalis Garganourakis