DEV Community

Paul Ikenna
Paul Ikenna

Posted on

Destructuring Props in React.js

Image descriptionFor 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>
)
}

Enter fullscreen mode Exit fullscreen mode

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>
)
}

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (2)

Collapse
 
tan_jung profile image
Na Bosseu

I though this way more better const Book = ({ title }) => { ... }

Collapse
 
fjones profile image
FJones

Yes and no. This is certainly quicker, aids slightly with completion, and makes code a bit more readable, but a crucial difference is that the variables are not declared as const in this syntax. This is generally not a problem, though, if you follow a solid codestyle and have a linter rule against reassigning props.