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: Hello World With function as children, you pass a function: {(data) => {data.message}} 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 {(data) => {data.message}} 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

Apr 27, 2025 - 08:04
 0
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 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