YogeshChauhan . com

How destructuring works in React?

in React on June 9, 2021

Destructuring is a small but a great concept that applies to arrays and objects both.

Destructuring feature was added in the ES6 specification of JavaScript.

In short, destructuring allows you to destructure values from objects and arrays.

Destructuring an object

In React, you pass the data via props to the components and use it like props.name, props.address via a dot operator.

Here’s an example of props object:

  props = {
    name: 'Yogesh Chauhan',
    address: 'Some Address',

Usually we use props like this:

  {props.name}'s address is {props.address}.

If you don’t want to use props.abc, props.xyz then you can just save the data into variables like this:

  let name = props.name;
  let address = props.address;

Now you can use those variables instead.

  {name}'s address is {address}.

That’s not it.

Destructuring makes your job easy when it comes to the assignment of variables.

You can just extract the values of an object’s properties and assign them to separate variables like this:

  let { name, address } = props

The order of those variables inside the bracket doesn’t matter!

That’s not it!

You can just directly pass that bracket with the variable names instead of props and it will work like a charm!

Let’s revisit the component helper function example.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Kubernetes vs. Docker? It’s a misleading phraseMiscCan Firewall and IDPS Stop DDoS Attack?MiscDifferent Types of Functions in JavaScriptJavaScriptWindow innerHeight and innerWidth properties in JavaScriptJavaScriptHigher Order Functions in JavaScript with ExamplesJavaScriptHow to enable GD library support for PHP on windows server?PHP