Published on

How to write HTMX with Tailwind Css and Shadcn UI?

Authors
  • Name
    Ripal & Zalak
    Twitter

The demand for lightweight, interactive web applications has led many developers to explore HTMX as an alternative to heavy client-side JavaScript frameworks. HTMX allows you to add dynamic behavior to your web pages using HTML attributes without the need for a separate JavaScript framework.

In this blog, we’ll explore how to use HTMX alongside Tailwind CSS and ShadCN UI in a Next.js project.


Why Use HTMX?

HTMX simplifies frontend development by enabling server-side rendering and dynamic updates through HTML attributes. It reduces complexity and improves performance, especially for small to medium-sized applications.

Key Features of HTMX:

  • Server-driven updates with HTML over the wire.
  • Simplified development with declarative HTML attributes.
  • No need for additional client-side JavaScript frameworks.

Setting Up HTMX in a Next.js Project

Here’s how you can integrate HTMX with a Next.js project while retaining Tailwind CSS and ShadCN UI.

Step 1: Install HTMX

Add HTMX to your project using a <script> tag in your HTML layout.

  1. Open your _app.js or _document.js file in your Next.js project.
  2. Include the HTMX script:
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <script src="https://unpkg.com/htmx.org" defer></script>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

Step 2: Install Tailwind CSS and ShadCN UI

If you haven’t already installed Tailwind CSS and ShadCN UI, follow these steps:

  1. Install Tailwind CSS:

    npm install -D tailwindcss postcss autoprefixer
    npx tailwindcss init
    

    Configure your tailwind.config.js:

    module.exports = {
      content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
      theme: {
        extend: {},
      },
      plugins: [],
    }
    
  2. Add ShadCN UI:

    Install ShadCN components by following the official documentation at ShadCN UI.


Using HTMX with Tailwind and ShadCN Components

Example: Dynamic Content with HTMX

Let’s create a simple HTMX-enabled component that uses Tailwind for styling and a ShadCN UI button.

  1. Server-Side Route:

    Create an API route (pages/api/hello.js) that serves HTML:

    export default function handler(req, res) {
      res.status(200).send('<p class="text-green-500">Hello from the server!</p>')
    }
    
  2. HTMX Component:

    Use HTMX attributes in a component:

    import { Button } from '@/components/ui/button'
    
    export default function HtmxExample() {
      return (
        <div className="p-8">
          <Button
            className="bg-blue-500 text-white"
            hx-get="/api/hello"
            hx-target="#response"
            hx-swap="innerHTML"
          >
            Fetch Data
          </Button>
          <div id="response" className="mt-4 text-gray-700"></div>
        </div>
      )
    }
    
    • hx-get: Specifies the URL to fetch.
    • hx-target: Defines where the response content should be rendered.
    • hx-swap: Controls how the content is updated (e.g., innerHTML, outerHTML, etc.).

Styling with Tailwind

Since ShadCN UI is built on Tailwind, you can use its utility classes to style your components dynamically. Combine Tailwind classes with HTMX attributes for seamless interactivity.


Enhancing HTMX with ShadCN Components

ShadCN UI components can be customized to work alongside HTMX. For example, modals, dropdowns, or toast notifications can be triggered with HTMX events.

Example: Triggering a Modal with HTMX

  1. Modal Component:

    import { Dialog, DialogTrigger, DialogContent } from '@/components/ui/dialog'
    
    export default function ModalExample() {
      return (
        <Dialog>
          <DialogTrigger className="bg-red-500 px-4 py-2 text-white">Open Modal</DialogTrigger>
          <DialogContent>
            <p className="text-gray-900">This is a modal triggered by HTMX.</p>
          </DialogContent>
        </Dialog>
      )
    }
    
  2. Trigger Modal via HTMX:

    Use an HTMX request to update the modal content dynamically:

    <button hx-get="/api/modal-content" hx-target="#modal-content" hx-swap="innerHTML">
      Load Modal Content
    </button>
    <div id="modal-content"></div>
    

Benefits of HTMX + Tailwind + ShadCN UI

  1. Lightweight and Fast: HTMX reduces the need for JavaScript frameworks, keeping the frontend lean.
  2. Dynamic Styling: Tailwind ensures consistent and responsive designs.
  3. Reusable UI Components: ShadCN UI components work seamlessly with HTMX for advanced interactivity.

Conclusion

By combining HTMX with Tailwind CSS and ShadCN UI, you can build highly interactive, lightweight web applications with server-driven content updates. This approach minimizes client-side complexity while leveraging the power of modern UI libraries.