DEV Community

Cover image for Using "Function as Children" in React
Nilupul Perera
Nilupul Perera

Posted on

Using "Function as Children" in React

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>
Enter fullscreen mode Exit fullscreen mode

With function as children, you pass a function:

<Component>
  {(data) => <div>{data.message}</div>}
</Component>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.