Understanding FunctionAsChild
The FunctionAsChild
pattern is gaining consensus within the React community. It is widely used in popular libraries like react-motion, which we will explore in Chapter 5, Writing Code for the Browser.
The main concept is that instead of passing a child as a component, we define a function that can receive parameters from the parent. Let’s see what it looks like:
const FunctionAsChild = ({ children }) => children()
As you can see, FunctionAsChild
is a component with a children property defined as a function. Instead of being used as a JSX expression, it gets called.
The preceding component can be used like this:
<FunctionAsChild>
{() => <div>Hello, World!</div>}
</FunctionAsChild>
This example is quite simple: the children function is executed within the parent’s render method, returning the Hello, World!
text wrapped in a div
tag, which is displayed on the screen.
Now, let’...