Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring object and ignore one of the results

I have:

const section = cloneElement(this.props.children, {   className: this.props.styles.section,   ...this.props, }); 

Inside this.props, I have a styles property that I don't want to pass to the cloned element.

How can I do?

like image 833
Fez Vrasta Avatar asked Jun 15 '16 14:06

Fez Vrasta


People also ask

Can you Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

What does object Destructuring us do?

The destructuring-assignment syntax is a JavaScript expression that allows us to unpack values from arrays or object properties into distinct variables.

Does order matter in object Destructuring?

Destructuring Objects What's even better, object destructuring can extract multiple properties in one statement. This makes the code clearer. The order of the properties does not matter.

How do I set default value in Destructuring?

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.


1 Answers

You can use the object rest/spread syntax:

// We destructure our "this.props" creating a 'styles' variable and // using the object rest syntax we put the rest of the properties available // from "this.props" into a variable called 'otherProps'  const { styles, ...otherProps } = this.props; const section = cloneElement(this.props.children, {   className: styles.section,   // We spread our props, which excludes the 'styles'   ...otherProps, }); 

I assume that you already have support from this syntax based on your code above, but please be aware that this is a proposed syntax which is made available to you via the babel stage 1 preset. If you get syntax errors on execution you can install the preset as follows:

 npm install babel-preset-stage-1 --save-dev 

And then add it to the presets section of your babel configuration. For example in your .babelrc file:

 "presets": [ "es2015", "react", "stage-1" ] 

Update based on comment on question by OP.

Okay, so you say that you already have a styles variable declared before this block? We can manage this case too. You can rename your destructured arguments to avoid this.

For example:

const styles = { foo: 'bar' };  const { styles: otherStyles, ...otherProps } = this.props; const section = cloneElement(this.props.children, {   className: otherStyles.section,   // We spread our props, which excludes the 'styles'   ...otherProps, }); 
like image 196
ctrlplusb Avatar answered Oct 04 '22 02:10

ctrlplusb