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 Worlddiv>
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.