Search code examples
next.jsnext.js13tailwind-uiheadless-uireact-server-components

How to use Tailwind UI (headless ui) components with Next JS server components?


I'm trying to build a web app on Next JS with Tailwind UI provided React components. Tailwind UI is using headless ui behind the scenes.

By default, Next JS will build server side components, unless you add 'use client' at the top of a page. Unfortunately, this seems to be a requirement instead of an option in case of Tailwind UI provided code, otherwise it will throw an error like this on the picture.

enter image description here

So the question is, how to use Tailwind UI components (to move fast with the development without being a front-end genius), but still have the option to use server components with Next JS?

What I tried

Tried using Tailwind UI components without 'use client', but they throw an error. Only solution is to add 'use client' at the top of the .tsx (or .jsx) file.


Solution

  • You do everything right, this is the Next.js problem. I just wrote a broad explanation of this behaviour. Please see https://stackoverflow.com/a/77077564/9047572

    TL:DR: you need that 'use client' directive to use client-only features. Once the component became client-side, its nested components are client-side too. No way to change or intercept this behavior.

    And TailwindCSS use some client-only features. Your error tells the same. It tells that headlessui.esm.js is a client-only component, so you can use this library in client-side components only.

    "Headless" doesn't mean it doesn't use some client-only bindings :)

    P.S. Short list of "client-only" features. Basically Nextjs will show you them in its errors, but anyway...

    • useX hooks from React and Nextjs: useEffect, useState, useContext, useRouter, useNavigation...
    • quite everything from react-dom, cause there is no possibility of DOM manipulation on the server side
    • browser event listeners like onChange.

    You better read the docs here

    P.P.S. Looks like there is another directory 'use server', which I didn't know of 2 days ago. Worth checking.