How to Use Headless UI with React: A Practical Guide

Headless UI offers fully accessible, unstyled React components that give you complete control over appearance and behavior. It integrates seamlessly with Tailwind CSS, but works with any styling approach. Here’s how to get started quickly.

First, install Headless UI via npm: npm install @headlessui/react. It provides components like Menu, Listbox, Combobox, Disclosure, and more—all with built-in keyboard navigation and ARIA attributes.

Article illustration

2. Basic Usage – A Menu Example

Import Menu and its sub-components. Wrap your trigger in Menu.Button, items in Menu.Items, and each option in Menu.Item.

  • Menu.Button – the clickable trigger
  • Menu.Items – the dropdown container
  • Menu.Item – individual selectable items (accepts a render prop)

Example:

<Menu> <Menu.Button>Options</Menu.Button> <Menu.Items> <Menu.Item>{({ active }) => ...}</Menu.Item> </Menu.Items> </Menu>

3. Styling with Tailwind or Custom CSS

Each component uses render props to pass state like active, selected, open. Use these to apply dynamic classes.

  • With Tailwind: className={`${active ? 'bg-blue-500' : ''}`}
  • With plain CSS: add a class conditionally

Because Headless UI doesn’t inject any styles, you have full design freedom.

4. Managing State and Transitions

Use React state (useState) for controlled components like Listbox. For animations, wrap the component with Transition from Headless UI to add enter/leave transitions easily.

<Transition show={isOpen} enter="transition duration-100" enterFrom="opacity-0" enterTo="opacity-100"> ... </Transition>

Wrapping Up

Headless UI gives you accessible, unstyled building blocks for menus, modals, tabs, and more. Combine with Tailwind or your own CSS to create polished UI without reinventing accessibility.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *