From 3f65c93b607b528d76fa9f2153e83a907c2c1833 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 11 Mar 2018 13:57:23 -0500 Subject: [PATCH] Add Dynamically Add Props To A Child Component as a react til --- README.md | 3 +- ...amically-add-props-to-a-child-component.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 react/dynamically-add-props-to-a-child-component.md diff --git a/README.md b/README.md index 48e0ebf..e41acf2 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/). -_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) diff --git a/react/dynamically-add-props-to-a-child-component.md b/react/dynamically-add-props-to-a-child-component.md new file mode 100644 index 0000000..95c6c11 --- /dev/null +++ b/react/dynamically-add-props-to-a-child-component.md @@ -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 ( + 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 ( + + Hello! + + ); +}; +``` + +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).