17

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?

kukumalu
  • 233
  • 1
  • 2
  • 14
  • 1
    Const isn't a variable, it's a keyword. That's *destructuring*, it's equivalent to `const plantTrees = this.props.plantTrees;`. – jonrsharpe Jun 24 '18 at 18:23

1 Answers1

38

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

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Djellal Mohamed Aniss
  • 1,723
  • 11
  • 24
  • thanks for your **great editing** @jonrsharpe , sorry new at stackoverflow – Djellal Mohamed Aniss Jun 24 '18 at 18:33
  • 2
    No worries, I'd suggest you read https://stackoverflow.com/editing-help to get to grips with the syntax. – jonrsharpe Jun 24 '18 at 18:34
  • 8
    This answered whats going on with the destructuring, but not why with a render() method in React one might want to wrap this.props as const versions of themselves? – Alex Schokking Jul 11 '18 at 03:59
  • 1
    In the codebase I work with, it seems to be done for concision. So you if you need `this.props.foo` several times in a function, all those references can simply be `foo`. – Paul Bissex Jul 08 '21 at 19:52