Functions as a child

Learn how you can pass a render function to a component as the children prop in an interactive fashion.

children prop

The value of a prop in JSX can be any valid JavaScript expression. As invoked functions can also return expressions, we can also use the return value of this function as a prop. Strings, booleans, arrays, objects, other React elements, and null can also be passed as props. The prop children is a special form, meaning that both of these lines will result in the same output when rendered:

<MyComponent>I am a child element</MyComponent>
<MyComponent children="I am a child element" />

The props.children function can be used to access “I am a child element” in MyComponent.

We can use this principle and also pass functions that are invoked during render() within a component. This way, data can be passed from one component into the next. The principle is similar to that of higher-order components, but offers a little more flexibility. We do not need to connect our component with a higher-order component but can simply be included within JSX in our current component.

Formatter component using Function as a Child

Thinking back to our withFormatting higher-order component, we could take a similar approach using a Function as a child:

Get hands-on with 1200+ tech skills courses.