1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Force A Component To Only Have One Child as a react til

This commit is contained in:
jbranchaud
2017-10-02 14:07:45 -05:00
parent 18e3cc18be
commit d54b358976
2 changed files with 51 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/).
_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)

View File

@@ -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 (
<SingleChildContainer>
<span>There can only be one!</span>
</SingleChildContainer>
);
}
}
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
<SingleChildContainer>
<span>There can only be one!</span>
<div>What about me?!</div>
</SingleChildContainer>
```
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.