・The main concept of FunctionAsChild that 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 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>
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.
・The primary advantage is the ability to encapsulate components, delivering variables dynamically, as opposed to utilizing static properties, which is a common practice with HOCs.An excellent illustration of this is a Fetch component, designed to retrieve data from a specific API endpoint and subsequently return it to its child function.
<Fetch url="...">
{data => <List data={data}/>}
</Fetch>
・Secondary, composing components with this approach does not force children to use predefined prop names. Since the function receives variables, developers who use the component can decide on their names.
This flexibility makes the Function as Child solution more versatile.
・lastly, the wrapper is highly reusable because it does not make any assumption about the children it receives it just expects a function.
Due to this, the same FunctionAsChild component can be used in different parts of the application it serves various children components.
Top comments (0)