How to use Tailwind CSS with Headless UI In React

In this section we will install tailwind v3 headless ui react. Headless UI is a set of completely unstyled, fully accessible UI components, designed to integrate beautifully with Tailwind CSS. it is also provide dropdown menu, lightbox, Switch (Toggle), Dialog (Modal), Popover, Radio Group, Transition, Tabs. So you can easily copy and paste code in you project.

Tool Use

Tailwind CSS 3.x

Headless UI

React JS

First you need to setup react project with tailwind css. You can install manually or you read below blog.

How to install Tailwind CSS in React

Install & Setup Vite + React + Typescript + Tailwind CSS 3

Install headless UI

To get started, install Headless UI via npm or yarn:

# npm
npm install @headlessui/react

# Yarn
yarn add @headlessui/react

Now lets test headless ui toggle code.

import { useState } from 'react'
import { Switch } from '@headlessui/react'

export default function App() {
  const [enabled, setEnabled] = useState(false)

  return (
    <div className="container mx-auto mt-20">
      <h1 className="text-xl font-bold ">
        Tailwind Headless UI {' '}
        <span className="text-transparent bg-clip-text bg-gradient-to-r from-green-400 via-blue-500 to-purple-600">
          Switch (Toggle)
        </span>
      </h1>
      <div className="ml-28">
        <Switch
          checked={enabled}
          onChange={setEnabled}
          className={`${enabled ? 'bg-teal-900' : 'bg-teal-700'}
          relative inline-flex flex-shrink-0 h-[38px] w-[74px] border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus-visible:ring-2  focus-visible:ring-white focus-visible:ring-opacity-75`}
        >
          <span className="sr-only">Use setting</span>
          <span
            aria-hidden="true"
            className={`${enabled ? 'translate-x-9' : 'translate-x-0'}
            pointer-events-none inline-block h-[34px] w-[34px] rounded-full bg-white shadow-lg transform ring-0 transition ease-in-out duration-200`}
          />
        </Switch>
      </div>
    </div>
  )
}
headless ui toggle

run project via npm or yarn.

# npm
npm start

# Yarn
yarn start

You can use more tailwind headless components in doc.

saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack