mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Destructure Variables As Props To A Component as a react til
This commit is contained in:
@@ -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/).
|
||||
|
||||
_621 TILs and counting..._
|
||||
_622 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -430,6 +430,7 @@ _621 TILs and counting..._
|
||||
- [Alter The Display Name Of A Component](react/alter-the-display-name-of-a-component.md)
|
||||
- [create-react-app Comes With Lodash](react/create-react-app-comes-with-lodash.md)
|
||||
- [Defining State In A Simple Class Component](react/defining-state-in-a-simple-class-component.md)
|
||||
- [Destructure Variables As Props To A Component](react/destructure-variables-as-props-to-a-component.md)
|
||||
- [Dispatch Anywhere With Redux](react/dispatch-anywhere-with-redux.md)
|
||||
- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md)
|
||||
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
|
||||
|
||||
45
react/destructure-variables-as-props-to-a-component.md
Normal file
45
react/destructure-variables-as-props-to-a-component.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# Destructure Variables As Props To A Component
|
||||
|
||||
When passing down props, a redundant-feeling pattern can sometimes emerge.
|
||||
|
||||
```javascript
|
||||
const MyComponent = ({ handleChange, handleBlur }) => {
|
||||
return (
|
||||
<div>
|
||||
<OtherComponent />
|
||||
<MySubComponent handleChange={handleChange} handleBlur={handleBlur} />
|
||||
</div>
|
||||
)
|
||||
};
|
||||
```
|
||||
|
||||
The typing feel duplicative, as if there ought to be a better way. One
|
||||
option is to simply pass down all the props:
|
||||
|
||||
```javascript
|
||||
<MySubComponent {...props} />
|
||||
```
|
||||
|
||||
This approach may result in passing down props that we don't intend to pass
|
||||
down and clutters the flow of data in our app.
|
||||
|
||||
Here is another approach:
|
||||
|
||||
```javascript
|
||||
const MyComponent = ({ handleChange, handleBlur }) => {
|
||||
return (
|
||||
<div>
|
||||
<OtherComponent />
|
||||
<MySubComponent {...{handleChange, handleBlur}} />
|
||||
</div>
|
||||
)
|
||||
};
|
||||
```
|
||||
|
||||
Here we are taking advantage of two ES6 features. Since the naming is the
|
||||
same, we can use [property
|
||||
shorthands](http://es6-features.org/#PropertyShorthand). Then we immediately
|
||||
use the [spread operator](http://es6-features.org/#SpreadOperator) to splat
|
||||
it back out as the props to the component.
|
||||
|
||||
h/t Vidal Ekechukwu
|
||||
Reference in New Issue
Block a user