Destructuring Props in React.js

Destructuring Props in React.js

For some time, I have been working with React, though still in the basics, I have learned new stuff that has helped me build component-based websites which that is basically what React is all about.

Out of curiosity to know more, especially in the basics before diving deeper into react fully, I decided to practice some ES6 methods in my project. as well all know, Es6 allows us to write less code but do more, which is one of the reasons I decided to try destructuring Props.

Props, a short name for property serves as an object that takes in value. These values are passed as attributes from a parent component and accessed on the child component through props.

I decided to share this today because I'm so happy my curiosity birthed this experience that I won't forget in a hurry.

Below, is how I normally pass and accept my props without destructuring.

import React from 'react';

const App = () => {
return(
 <React.Fragment>
   <Book title="Hello World"/>
</React.Fragment>
)
}

// Second component
import React from 'react';

const Book = (props) => {
 return (
<React.Fragment>
   <h1>{props.title}<h1/>
</React.Fragment>
)
}

Here I pass the title attribute with a value of string 'Hello World", from my Parent component(App) to my child component (Book), The Book now receives this value using props.title(the specifies it to be an object).

Below is the new way I do this same thing using destructuring.

import React from 'react';

const App = () => {
return(
 <React.Fragment>
   <Book title="Hello World"/>
</React.Fragment>
)
}

// Second component
import React from 'react';
//The first Instance
const Book = (props) => {
const {title} = props;
 return (
<React.Fragment>
   <h1>{title}<h1/>
</React.Fragment>
)
}

In the above code, I unpacked the value of the title from props which is an object and encoded my title to the h1, as simple as that. this method is very easy to use, especially when you have multiple values from the parent-to-child component.

Destructuring, lessen your code and also help you to stop repeating yourself. for me, it is a more proper and easy way to do things. You should try it out sometime.