Course contentsShow
← React
Lesson 2345 of 2,39651. TypeScript with React BasicsFree lesson

Children as Render Props

Type children as functions with signatures like (data: T) => ReactNode for render prop patterns.

Children as Render Props

What you'll learn: How to type children when it's a function that receives data and returns JSX, enabling flexible render prop patterns.


The Render Prop Pattern with Children

Sometimes you want a component to pass data to its children instead of just rendering them directly. The "children as render prop" pattern treats children as a function that receives data and returns what to render:

interface DataProviderProps<T> {
  data: T;
  children: (data: T) => ReactNode;
}

function DataProvider<T>({ data, children }: DataProviderProps<T>) {
  return <>{children(data)}</>;
}

Notice children isn't ReactNode anymore—it's a function signature (data: T) => ReactNode. This tells TypeScript: "children must be a function that accepts data of type T and returns something renderable."

Using It

<DataProvider data={{ name: "Alice", age: 30 }}>
  {(user) => (
    <div>
      {user.name} is {user.age}
    </div>
  )}
</DataProvider>

TypeScript infers user has properties name and age because the generic T flows through. The function child gets type-safe data access.

Multiple Arguments

You can pass multiple values:

interface ListProps<T> {
  items: T[];
  children: (item: T, index: number) => ReactNode;
}

function List<T>({ items, children }: ListProps<T>) {
  return <>{items.map((item, i) => children(item, i))}</>;
}

This pattern is powerful for lists, data fetching wrappers, or any component that needs to invert control—letting the parent decide how to render while the child provides what to render.

Key Takeaway: Type children as a function signature like (data: T) => ReactNode when implementing render prop patterns, giving consumers type-safe access to the data your component provides.