There is a pattern that is gaining consensus within the React community, called Function as Child.
It is widely used in the popular library react-motion, which we will see in Chapter 6, Write Code for the Browser.
The main concept is that, instead of passing a child in the form of a component, we define a function that can receive parameters from the parent.
Let's see what it looks like:
const FunctionAsChild = ({ children }) => children() FunctionAsChild.propTypes = { children: React.PropTypes.func.isRequired, }
As you can see, FunctionAsChild
is a component that has a children property defined as a function and, instead of being used as a JSX expression, it gets called.
The preceding component can be used in the following way:
<FunctionAsChild> {() => <div>Hello, World!</div>} </FunctionAsChild>
It is as simple as it looks: the children function is fired in the render method of the parent and...