|
| 1 | +--- |
| 2 | +id: function-as-child-component |
| 3 | +sidebar_label: Function as child component |
| 4 | +title: Function as Child Component |
| 5 | +description: Function as child component | React Patterns, techniques, tips and tricks in development for Ract developer. |
| 6 | +keywords: ['function as child component', 'child component', 'reactpatterns', 'react patterns', 'reactjspatterns', 'reactjs patterns', 'react', 'reactjs', 'react techniques', 'react tips and tricks'] |
| 7 | +version: Function as child component |
| 8 | +image: /img/reactpatterns-cover.png |
| 9 | +--- |
| 10 | + |
| 11 | +## What is Function as Child Component? |
| 12 | + |
| 13 | +A Function as child component is a pattern that lets you pass a render function to a component as the children prop so you can change what you can pass as children to a component. |
| 14 | + |
| 15 | +## Usage |
| 16 | + |
| 17 | +When you use a Function as child component, instead of passing JSX markup, you assign children as a function. |
| 18 | + |
| 19 | +```jsx |
| 20 | +<Foo> |
| 21 | + {(name) => <div>`hello from ${name}`</div>} |
| 22 | +</Foo> |
| 23 | +``` |
| 24 | + |
| 25 | +And the `Foo` component would look something like this. |
| 26 | + |
| 27 | +```jsx |
| 28 | +const Foo = ({ children }) => { |
| 29 | + return children('foo') |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +## For examples |
| 34 | + |
| 35 | +Let take a look at a advanced example of a Function as child component. |
| 36 | + |
| 37 | +```jsx |
| 38 | +import React from 'react' |
| 39 | + |
| 40 | +class PageWidth extends React.Component { |
| 41 | + state = { width: 0 } |
| 42 | + |
| 43 | + componentDidMount() { |
| 44 | + this.setState({ width: window.innerWidth }) |
| 45 | + |
| 46 | + window.addEventListener( |
| 47 | + 'resize', |
| 48 | + ({ target }) => { |
| 49 | + this.setState({ width: target.innerWidth }) |
| 50 | + } |
| 51 | + ) |
| 52 | + } |
| 53 | + |
| 54 | + render() { |
| 55 | + const { width } = this.state |
| 56 | + |
| 57 | + return this.props.children(width) |
| 58 | + } |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +And then you could use it as. |
| 63 | + |
| 64 | +```js |
| 65 | +<PageWidth> |
| 66 | + {width => <div>Page width is {width}</div>} |
| 67 | +</PageWidth> |
| 68 | +``` |
| 69 | + |
| 70 | +As you can see above, children is "overloaded" and passed to `PageWidth` as a function instead of being a `ReactNodeList` as nature intended. The `PageWidth` component's render method calls `this.props.children` (passing it width), which returns rendered JSX. |
| 71 | + |
| 72 | +The real power of [render callbacks](render-callback.md) can be seen in this example. `PageWidth` will do all of the heavy lifting, while exactly what is rendered can change, depending on the render function that is passed. |
0 commit comments