From d54b35897628a24bf070d44fc6a8df85447362dc Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 2 Oct 2017 14:07:45 -0500 Subject: [PATCH] Add Force A Component To Only Have One Child as a react til --- README.md | 7 ++- ...orce-a-component-to-only-have-one-child.md | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 react/force-a-component-to-only-have-one-child.md diff --git a/README.md b/README.md index d00b286..d04028d 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/). -_569 TILs and counting..._ +_570 TILs and counting..._ --- @@ -32,6 +32,7 @@ _569 TILs and counting..._ * [Phoenix](#phoenix) * [PostgreSQL](#postgresql) * [Rails](#rails) +* [React](#react) * [Ruby](#ruby) * [tmux](#tmux) * [Unix](#unix) @@ -402,6 +403,10 @@ _569 TILs and counting..._ - [Truncate Almost All Tables](rails/truncate-almost-all-tables.md) - [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md) +### React + +- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md) + ### Ruby - [Are They All True?](ruby/are-they-all-true.md) diff --git a/react/force-a-component-to-only-have-one-child.md b/react/force-a-component-to-only-have-one-child.md new file mode 100644 index 0000000..44aa689 --- /dev/null +++ b/react/force-a-component-to-only-have-one-child.md @@ -0,0 +1,45 @@ +# Force A Component To Only Have One Child + +A component can normally have an arbitrary number of elements nested +directly inside it. React's `Children.only` function can be used to force it +to a single direct child. + +```javascript +import React, { Children, Component } from "react"; + +class App extends Component { + render() { + return ( + + There can only be one! + + ); + } +} + +const SingleChildContainer = props => { + return Children.only(props.children); +}; + +export default App; +``` + +The React docs describe the behavior of `Children.only` as such, +_"Returns the only child in children. Throws otherwise."_. + +If you modify the `return` in `App` to contain the following JSX + +```javascript + + There can only be one! +
What about me?!
+
+``` + +then an error will be thrown (`React.Children.only expected to receive a +single React element child`). + +The [`Provider` +component](https://github.com/reactjs/react-redux/blob/master/src/components/Provider.js#L36) +in [`react-redux`](https://github.com/reactjs/react-redux) is an example of +where this is used.