Reputation: 313
Came across these 2 notations recently. While both appear to be doing similar things, one of them uses an assignment operator while another one appears to be an object. Are they doing anything different?
const { value = "" } = this.props;
and
let { value: newValue } = newProps;
Upvotes: 3
Views: 70
Reputation: 36179
It has nothing to do with React library actually. They are ES6 destructuring assignments.
The first example will create a constant variable called value
and will assign whatever is this.props.value
(Object, Array, Number). If this.props.value
is undefined though it will use default value = ""
- empty string.
const { value = "" } = this.props;
In a second example, newValue
variable will be created and it will equal to newProps.value
(even if it is undefined).
let { value: newValue } = newProps;
Upvotes: 4
Reputation: 2738
Both of these are destructing an object. When you use =
you are setting a default value if the value is undefined/null. With :
you are aliasing the variable. You can even combine them:
const { value : value2 = 'Hello' } = this.props;
console.log(this.props.value); // World
console.log(value2); // World (since value2 IS this.props.value aliased)
// ...or if this.props.value isn't defined
console.log(value2); // Hello
Upvotes: 4