You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.markdown
+12-19Lines changed: 12 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -358,35 +358,28 @@ Many developers favor [Higher Order Components](#higher-order-component) for thi
358
358
359
359
## Children pass-through
360
360
361
-
You might create a component designed to apply `context` and render its `children`.
361
+
There are times you'll need to wrap a stateless function with lifecycle events.
362
+
While we want to wrap component functionality around other components, we don't want to introduce extraneous DOM nodes.
363
+
In some apps, this might brake styling.
364
+
365
+
We use the function `React.Children.only`.
366
+
`only` allows us to return `this.props.children`__if__ there is only one child.
367
+
Otherwise, it throws an error.
362
368
363
369
```js
364
-
classSomeContextProviderextendsReact.Component {
365
-
getChildContext() {
366
-
return {some:"context"}
370
+
classSomeLifeCycleWrapperextendsReact.Component {
371
+
componentDidMount() {
372
+
console.log("I mounted but have no DOM.")
367
373
}
368
374
369
375
render() {
370
-
// how best do we return `children`?
376
+
returnReact.Children.only(this.props.children)
371
377
}
372
378
}
373
379
```
374
380
375
-
You're faced with a decision. Wrap `children` in an extraneous `<div />`or return `children` directly. The first options gives you extra markup (which can break some stylesheets). The second will result in unhelpful errors.
381
+
In cases where you're working with `state`or `context`, prefer [higher-order components](#higher-order-component) or [render callbacks](#render-callback).
376
382
377
-
```js
378
-
// option 1: extra div
379
-
return<div>{children}</div>
380
-
381
-
// option 2: unhelpful errors
382
-
return children
383
-
```
384
-
385
-
It's best to treat `children` as an opaque data type. React provides `React.Children` for dealing with `children` appropriately.
0 commit comments