Course contentsShow
← React
Lesson 1059 of 2,39627. Composition: Render PropsFree lesson

Fallback Rendering When Children is Not a Function

Handling cases where children might be JSX or a function, providing sensible defaults for both.

Fallback Rendering When Children is Not a Function

You'll learn how to make your render prop components flexible by handling both function children and regular JSX children gracefully.

The Problem with Rigid Expectations

When you build a component that uses the function-as-children pattern, you're assuming children will always be a function. But what if someone passes regular JSX instead? Your component will crash trying to call children() on something that isn't callable.

The solution is to check whether children is actually a function before invoking it, and provide a sensible fallback when it's not.

Implementing a Fallback Strategy

Think of it like a restaurant that specializes in custom orders but also has a default menu. If a customer gives specific instructions (a function), you follow them. If they don't (regular JSX), you serve the standard option.

Here's the pattern:

function DataProvider({ children, data }) {
  // Check if children is a function
  if (typeof children === 'function') {
    return children(data);
  }
  
  // Otherwise, render children as-is
  return children;
}

Now your component works both ways:

<DataProvider data={user}>
  {(data) => <p>{data.name}</p>}
</DataProvider>

<DataProvider data={user}>
  <p>Static content works too!</p>
</DataProvider>

Why This Matters

This defensive pattern makes your components more resilient and user-friendly. It prevents cryptic errors and allows developers to use your component in simpler scenarios where dynamic rendering isn't needed. The component degrades gracefully rather than breaking.

Key Takeaway: Always check typeof children === 'function' before invoking function children, and provide a fallback that renders regular children to make your render prop components flexible and error-resistant.