Course contentsShow
← React
Lesson 1103 of 2,39628. Composition: Compound ComponentsFree lesson

Headless UI's Render Prop Alternative

See how Headless UI provides render props for accessing internal state like open/selected.

Headless UI's Render Prop Alternative

What you'll learn: How Headless UI components use render props to expose internal state like open or selected to your custom UI.

The Concept

While Headless UI primarily relies on Context for compound components (like we just learned), it also offers a render prop escape hatch. Instead of blindly rendering children, certain components accept a function as children that receives the component's internal state as arguments.

This lets you access state like "is this menu open?" or "is this tab selected?" to customize rendering without wrapping everything in a Context consumer.

How It Works

<Menu>
  {({ open }) => (
    <>
      <Menu.Button>
        Options {open ? '▲' : '▼'}
      </Menu.Button>
      <Menu.Items>
        <Menu.Item>Account</Menu.Item>
        <Menu.Item>Sign Out</Menu.Item>
      </Menu.Items>
    </>
  )}
</Menu>

The Menu component calls your function with { open: true } or { open: false }. You use that state to conditionally render arrows, classes, or entirely different UI.

Why This Matters

This pattern gives you granular control without requiring a separate useMenuContext() hook. It's especially useful for:

  • Dynamic icons based on state
  • Conditional CSS classes
  • Accessibility attributes that depend on internal state
  • Animation triggers

Analogy

Think of it like a restaurant letting you peek into the kitchen. Instead of just receiving your meal (rendered children), you get a window ({ open }) to see what's cooking, so you can adjust your table settings accordingly.

Key Takeaway: Headless UI combines compound components with render props, letting you access internal state like open or selected by passing a function as children instead of just JSX.