Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: why use const {} = this.props and why put it inside the render function [duplicate]

Tags:

reactjs

I am learning reactjs and I see many people write, for example

class Trees extends Component {

    render() {
        const { plantTrees } = this.props;
        return( ...

I want to know why use const {} = this.props? Is there any benefit to using it? what is the purpose of initializing the const variable inside the render function?

like image 753
kukumalu Avatar asked Jun 24 '18 18:06

kukumalu


1 Answers

In reality this is not only for React, but it's an ES6 feature for JavaScript called destructuring assignment, it's a better way to retrieve values from an object or an array. In your example, without ES6 we must use

const plantTrees = this.props.plantTrees;

but with ES6 we simply use

const { plantTrees } = this.props

In the case of an array, we can use this

const [,price] = ['car',10000]

to retrieve the second element on the array and store it on a constant called price.

More information here: https://javascript.info/destructuring-assignment

like image 186
Djellal Mohamed Aniss Avatar answered Oct 18 '22 03:10

Djellal Mohamed Aniss