Is it Good to Destructure Props in React?

Destructure Props React

In this article, we will see about destructure props in React. Destructuring is an ES6 feature that makes it possible to unpack values from arrays or properties from objects into distinct variables. In react, restructuring props improves code readability. Let’s start with functional components.

There are two ways to destructure props in a functional component. The first way is to destructure it in the function parameter itself.

Destructuring in the parameter:

Ex:

const greet = (props) => {
    return(
    <div>           
            <h1>Hello {props.name}, Your age is {props.age}</h1>
     </div>
     
    )   
}

In the above, we have created props functional component. We passed “props” as a function parameter.
So, instead of passing “props” parameter, we can put destructuring using curly braces {name, age}. We are basically extracting name and age from the props object.
In the JSX, we can now use {name} {age} instead of {props.name} {props.age}. So, after destructuring our code is like below:

const greet = ({name,age}) => {
    return(
    <div>           
            <h1>Hello {name}, Your age is {age}</h1>
     </div>
     
    )   
}

See the output, still it return same content.
Output:

destructure props react

Destructuring in the function body:

const comment = (props) => {
    const {name, age} = props
    return(
    <div>           
            <h1>Hello {name}, Your age is {age}</h1>
     </div>
     
    )   
}

The above code is an example of destructuring in the function body. Here, we have passed the “props” as a parameter.
Then in the body of functional component, we assigned const{name,age} to props. So, we extract the name and age properties from the props object.
After this, we use {name} and {age} in the JSX. See the above code is still work as expected.

READ ALSO  Variable vs Constant in Javascript | Step-by-Step Guide

destructure props react

So, these are the two ways to destructuring props in a functional component.

 

 

Leave a Reply