In React, we often pass static JSX or components as children to other components.
But what if children could be a function instead of plain JSX?
This is exactly what the Function as Children (or Render Props) pattern allows.
β What is Function as Children?
Normally, you'd pass JSX like this:
<Component>
<div>Hello World</div>
</Component>
With function as children, you pass a function:
<Component>
{(data) => <div>{data.message}</div>}
</Component>
Here, the child is a function that receives data (or any parameter) from the parent component!
β Why Use Function as Children?
Flexibility:
Components can offer dynamic control over their rendering.Reusability:
You don't need to hard-code rendering logic inside the component itself.Composition:
Share behavior without restricting the structure of the UI.
β Example
type DataProviderProps = {
children: (data: { message: string }) => React.ReactNode;
};
const DataProvider = ({ children }: DataProviderProps) => {
const data = { message: 'Hello from DataProvider!' };
return <>{children(data)}</>;
};
// Usage
<DataProvider>
{(data) => <h1>{data.message}</h1>}
</DataProvider>
Here, DataProvider
controls what data is passed, but the consumer controls the UI!
β Real-world Use Cases
- Tooltips that need access to the anchor position
- Tables where rows are rendered dynamically
- List views with custom item templates
- Modals and portals
- Resizable panels or draggable elements
π Key Takeaways
- Think of it as "children, but smarter."
- Use it when you want to give control back to the component user.
- Keep it simple: only use it when necessary to avoid overcomplicating your code.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.