1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Dynamically Add Props To A Child Component as a react til

This commit is contained in:
jbranchaud
2018-03-11 13:57:23 -05:00
parent e3097af2f7
commit 3f65c93b60
2 changed files with 41 additions and 1 deletions

View File

@@ -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/).
_637 TILs and counting..._
_638 TILs and counting..._
---
@@ -443,6 +443,7 @@ _637 TILs and counting..._
- [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)
- [Dynamically Add Props To A Child Component](react/dynamically-add-props-to-a-child-component.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)
- [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md)

View File

@@ -0,0 +1,39 @@
# Dynamically Add Props To A Child Component
If your component has an element nested in it, then it will receive a
`children` prop. There are a number of things you can do beyond simply
including the `children` as part of the rendered output of the component.
One thing you can do is put additional props on the child.
```javascript
const ParentWithClick = ({ children }) => {
return (
<children.type
{...children.props}
onClick={() => alert("You clicked me!")}
/>
);
};
```
This `ParentWithClick` component will reconstitute its child component with
its given props and a new `onClick` prop.
Here is how it can be used:
```javascript
const App = () => {
return (
<ParentWithClick>
<span>Hello!</span>
</ParentWithClick>
);
};
```
Click on `Hello!` and you'll see the alert.
Minor caveat: multiple children and a string child will need to be handled
differently.
See a [live example here](https://codesandbox.io/s/n0pyn61yop).