Open In App

Destructuring of Props in ReactJS

Destructuring is a simple property that is used to make code much clear and readable, mainly when we pass props in React.

What is Destructuring?



Advantages of Destructuring:

How to use Destructuring?



We can use the Destructuring in the following method in ReactJS:

1. Using this.props method

In this example, we are going to simply display some words using destructuring and without destructuring.

Project Structure: It will look like the following.

Destructuring gives access to the use of props in a more readable format and discards the need for props for every property.

App.js: Now write down the following code in the App.js file. Here, App is our default component where we will print our component code.




import React from "react"
import Greet from './component/Greet'
    
 class App extends React.component{
   render(){
     return(
       <div className = "App">
                 <Greet active="KAPIL GARG"  activeStatus = "CSE"/>
       </div>
    );
  }
}
export default App;

Greet.js: In this file, We will write component code about the destructuring process.

2. Using the Extraction method:

There are many times when the value extracted during Destructuring no more exist, then in this condition we can use of default behavior of Destructuring, in this, apply a default value to the newly declared properties of Destructuring

In the following code, the activeObject will be set true if it is undefined in this.props.

Const {active, activeStatus, activeObject = true } = this.props

3. Using the Re-assigning method:

A variable name that is not a copy of the property being destructured may be used. This is achieved by reassigning as shown below.

In the following code, the properties active, activeStatus have been destructured and reassigned as variables named generating, objectMessage.

const { active : generating, activeStatus : objectMessage} = this.props

Article Tags :