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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With