DEV Community

mustafa morbel
mustafa morbel

Posted on Originally published at javascript.plainenglish.io

HTML Native Dialog Component in React with Tailwind CSS

Originally published on Medium (JavaScript in Plain English). Read on Medium for free via Friend Link.

⚡ Get the Production-Ready React Hooks Pack

Native HTML dialog modal component in React styled with Tailwind CSS showing backdrop and form controls

Building an interactive, backdrop-ready modal in React using the native HTML <dialog> element and Tailwind CSS.

Quick Takeaways

  • Zero modal dependencies : The native <dialog> element gives you showModal(), close(), top-layer rendering, and Escape-key dismissal out of the box.
  • Click-outside and lifecycle events : Pair getBoundingClientRect() with native close and cancel events to handle backdrop clicks and state sync cleanly.
  • Tailwind CSS animations : Combine open: and backdrop: variants with custom @keyframes in tailwind.config.js for smooth fade-in transitions.

Building a modal in React usually starts with installing a third-party library. Yet modern browsers already ship a powerful primitive built right into HTML: the <dialog> element.

In this guide, we will walk through creating an interactive HTML Native Dialog component broken into four practical parts: native <dialog> basics, backdrop clicks and events, CSS and Tailwind animations, and the complete React TypeScript component.


1. Native HTML <dialog> Basics

At its core, <dialog> handles top-layer stacking, focus trapping, and form integration without extra JavaScript plumbing. Here is a minimal HTML example with a trigger button, a dialog form, and showModal() / close() handlers:

<button
  type="button"
  onclick="openDialog()"
>
  Open Dialog
</button>

<dialog id="nativeDialog">
  <form method="dialog">
    <input
      type="text"
      placeholder="Enter your name"
    />
    <button type="submit">Submit</button>
    <button
      formmethod="dialog"
      type="reset"
      onclick="closeDialog()"
    >
      Cancel
    </button>
  </form>
</dialog>

<script>
  function openDialog() {
    const dialog = document.getElementById(
      "nativeDialog"
    );
    dialog.showModal();
  }

  function closeDialog() {
    const dialog = document.getElementById(
      "nativeDialog"
    );
    dialog.close();
  }
</script>
Enter fullscreen mode Exit fullscreen mode

The dialog box contains a form with a name input and two buttons for submission and cancellation. Calling showModal() displays the dialog in the browser's top layer with a built-in backdrop.


2. Handling Events and Backdrop Clicks

Closing the modal with the Escape key comes included by default when using <dialog>. You can also listen for clicks directly on the dialog element to close it when the user clicks the backdrop:

const dialog = document.querySelector("dialog");
dialog?.addEventListener("click", (e: MouseEvent) => {
  if (e.target === dialog) {
    // close the dialog
    dialog.close();
  }
});
Enter fullscreen mode Exit fullscreen mode

To react when the modal finishes closing, attach a listener for the native close event:

const dialog = document.querySelector("dialog");
dialog?.addEventListener("close", () => {
  console.log("dialog closed");
});
Enter fullscreen mode Exit fullscreen mode

Note that the close event fires when the dialog closes normally, whereas pressing Escape triggers a cancel event first.

What if your dialog contains nested elements or padding that makes e.target === dialog unreliable? You can calculate the dialog's bounding box with getBoundingClientRect() and close it whenever a click lands outside those coordinates:

const dialog = document.querySelector("dialog");
dialog?.addEventListener("click", (e: MouseEvent) => {
  const rect = dialog.getBoundingClientRect();
  if (
    e.clientX < rect.left ||
    e.clientX > rect.right ||
    e.clientY < rect.top ||
    e.clientY > rect.bottom
  ) {
    dialog.close();
  }
});
Enter fullscreen mode Exit fullscreen mode

This approach checks the pointer coordinates against the dialog's rendered rectangle, ensuring clicks outside the modal surface always dismiss it cleanly.


3. Animating <dialog> and ::backdrop in CSS & Tailwind

By default, a native <dialog> snaps open and shut without transitions. You can add a smooth fade-in in plain CSS by targeting dialog[open] and dialog[open]::backdrop:

@keyframes fade-in {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

dialog {
  /* Initially invisible */
  opacity: 0;
}

dialog[open] {
  opacity: 1;
  animation: fade-in 0.5s ease-in-out;
}

dialog::backdrop {
  /* Styles for the backdrop */
}

dialog[open]::backdrop {
  opacity: 1;
  animation: fade-in 0.5s ease-in-out;
}
Enter fullscreen mode Exit fullscreen mode

Add Animation to Tailwind CSS

To bring that same transition into Tailwind CSS, register the fade-in keyframe and animation inside your tailwind.config.js file:

module.exports = {
  // ...
  theme: {
    extend: {
      keyframes: {
        "fade-in": {
          "0%": { opacity: "0%" },
          "100%": { opacity: "100%" },
        },
      },
      animation: {
        "fade-in": "fade-in 0.5s ease-in-out",
      },
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

Once configured, you can apply the effect to both the dialog and its backdrop using Tailwind's open: and backdrop: modifiers:

<dialog
  class="
    open:animate-fade-in
    open:backdrop:animate-fade-in
  "
>
  ...
</dialog>
Enter fullscreen mode Exit fullscreen mode

4. HTML Native Dialog Component in React with Tailwind CSS

Now let's combine useRef, useEffect, native <dialog> events, and Tailwind CSS into a complete React TypeScript component:

import React, { useRef, useEffect } from "react";
import classNames from "classnames";

const HtmlDialog: React.FC = () => {
  const dialogRef = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return;

    const handleBackdropClick = (e: MouseEvent) => {
      const rect = dialog.getBoundingClientRect();
      if (
        e.clientX < rect.left ||
        e.clientX > rect.right ||
        e.clientY < rect.top ||
        e.clientY > rect.bottom
      ) {
        dialog.close();
      }
    };

    const handleClose = () => {
      console.log("dialog closed");
    };

    const handleCancel = (event: Event) => {
      console.log("dialog cancelled");
      event.preventDefault();
    };

    dialog.addEventListener("click", handleBackdropClick);
    dialog.addEventListener("close", handleClose);
    dialog.addEventListener("cancel", handleCancel);

    return () => {
      dialog.removeEventListener(
        "click",
        handleBackdropClick
      );
      dialog.removeEventListener("close", handleClose);
      dialog.removeEventListener("cancel", handleCancel);
    };
  }, []);

  const primaryBtn = classNames(
    "rounded-lg border border-sky-600 bg-sky-800",
    "px-5 py-2.5 text-sm font-medium text-sky-100",
    "hover:bg-sky-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  const cancelBtn = classNames(
    "rounded-lg border border-slate-600 bg-slate-800",
    "px-5 py-2.5 text-sm font-medium text-slate-400",
    "hover:bg-slate-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  const resetBtn = classNames(
    "rounded-lg border border-red-600 bg-red-800",
    "px-5 py-2.5 text-sm font-medium text-red-100",
    "hover:bg-red-700 hover:text-white",
    "focus:z-10 focus:outline-none focus:ring-0"
  );

  return (
    <section
      className="flex flex-col items-center py-12"
    >
      <button
        type="button"
        className={primaryBtn}
        onClick={() => dialogRef.current?.showModal()}
      >
        Open Dialog
      </button>

      <dialog
        ref={dialogRef}
        className={classNames(
          "inset-0 bg-zinc-50 bg-opacity-90",
          "backdrop:bg-slate-600 backdrop:bg-opacity-50",
          "open:animate-fade-in",
          "open:backdrop:animate-fade-in"
        )}
      >
        <div
          className="flex flex-col items-center gap-3 p-8"
        >
          <h1 className="text-4xl font-bold">Dialog</h1>
          <span>You can see me</span>
          <form
            method="dialog"
            className="flex flex-col gap-3"
          >
            <input
              type="text"
              placeholder="Enter your name"
              className={classNames(
                "rounded-md border-2 border-gray-300",
                "px-3 py-2 focus:border-transparent",
                "focus:outline-none focus:ring-2",
                "focus:ring-indigo-400"
              )}
            />

            <button type="submit" className={primaryBtn}>
              Submit
            </button>

            <button
              formMethod="dialog"
              type="submit"
              className={cancelBtn}
            >
              Cancel
            </button>

            <button
              type="reset"
              className={resetBtn}
              onClick={() => {
                dialogRef.current?.close();
                setTimeout(() => {
                  dialogRef.current?.showModal();
                }, 0);
              }}
            >
              Reset
            </button>
          </form>
        </div>
      </dialog>
    </section>
  );
};

export default HtmlDialog;
Enter fullscreen mode Exit fullscreen mode

Tip : Notice how event.preventDefault() inside the cancel listener lets you intercept Escape-key dismissal when you need to confirm unsaved form changes before closing.


Keep Exploring


Are you still reaching for third-party modal packages, or have you already switched to native <dialog> in production? I'd love to hear your experience 🧠💬

Written by Mustafa Morbel — software engineer and technical writer with over 17 years of experience building web applications with React, TypeScript, and modern frontend architectures.

Top comments (0)