diff --git a/README.md b/README.md index 4e11e15..267940c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_739 TILs and counting..._ +_740 TILs and counting..._ --- @@ -254,6 +254,7 @@ _739 TILs and counting..._ - [Create Bootstrapped Apps With Yarn](javascript/create-bootstrapped-apps-with-yarn.md) - [Custom Type Checking Error Messages With Yup](javascript/custom-type-checking-error-messages-with-yup.md) - [Default And Named Exports From The Same Module](javascript/default-and-named-exports-from-the-same-module.md) +- [Destructure With Access To Nested Value And Parent Value](javascript/destructure-with-access-to-nested-value-and-parent-value.md); - [Destructuring The Rest Of An Array](javascript/destructuring-the-rest-of-an-array.md) - [Enable ES7 Transforms With react-rails](javascript/enable-es7-transforms-with-react-rails.md) - [Easy Date Comparison With DayJS](javascript/easy-date-comparison-with-dayjs.md) diff --git a/javascript/destructure-with-access-to-nested-value-and-parent-value.md b/javascript/destructure-with-access-to-nested-value-and-parent-value.md new file mode 100644 index 0000000..b11d54f --- /dev/null +++ b/javascript/destructure-with-access-to-nested-value-and-parent-value.md @@ -0,0 +1,46 @@ +# Destructure With Access To Nested Value And Parent Value + +A destructuring pattern that I often see (especially in React code) is to +peel off a nested value in the argument declaration of a function. + +```javascript +const Component = ({ data: { name: displayName }}) => { + return ( +
+

{displayName}

+ +
+ ); +}; +``` + +On its own this works quite well, but what happens when you need access to +the full set of `data` as well as the nested `name` value? I often see this. + +```javascript +const Component = ({ data }) => { + const { name: displayName } = data; + return ( +
+

{displayName}

+ +
+ ); +}; +``` + +ES6 destructuring is flexible. You can skip the `const` line and keep +everything in the argument declaration. + +```javascript +const Component = ({ data: { name: displayName }, data }) => { + return ( +
+

{displayName}

+ +
+ ); +}; +``` + +You can re-reference the `data` value after the nested destructuring.