Destructuring in React

const { name } = this.props
props = {
author: {
name: "David Sedaris",
residence: {
city: "Rackham",
province: "West Sussex"
}
},
review: "",
date: "April 08, 2021"
};
import React, { Component } from "react";class AuthorDetails extends Component {

render() {
const { author } = this.props;
const { residence } = author;
return (
<div>
...
</div>
);
}
}
export default AuthorDetails;
const { author: { residence: { city, province } } } = this.props;
return (
<div>
<p>City: {city}</p>
<p>Province: {province}</p>
</div>
);

Rest syntax

Another feature at our disposal is the rest syntax, which is denoted by three dots (...). There may be a little confusion here as the rest syntax uses the same pattern as the spread operator but their purposes differ. In our destructuring assignment, we can group any remaining properties into their own variable. You can think of it as "what do I want to do with the rest of this data?" This is an effective way to group additional pieces of data together:

const { author, ...rest } = this.props;console.log(author); 
//{ name: "David Sedaris", residence: {…} }
console.log(rest);
//{ review: "", date: "April 08, 2021" }
const {...rest, author  } = props; 🛑
const { author, ...rest } = props; ✅

Variable renaming

Another convenient feature of destructuring is the ability to rename properties so they better convey more meaning or context for our code. When working with external data like an API, we may have data returned to us that is poorly named or shares the same name for variables we are already using. When we are extracting values, we can rename those values with the : character like so:

const { author } = props;const { residence: origin, name: fullName } = author;console.log(origin);     
// { city: "Rackham", province: "West Sussex" }
console.log(fullName);
// "David Sedaris"

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store