Feature blog image

Dark mode with Ladle and TailwindCSS

2 min read

In Ladle there is a handy button which is able to switch between light and dark mode. However, this only switches the ui of Ladle. Wouldn't it be great if it could also switch the mode of our TailwindCSS components, with the same button? It turns out that we can. We only have to create a GlobalProvider.

The GlobalProvider

A global provider can be used to enhance stories or provide additional context to them. In this example we use the class strategy to toggle the dark mode in TailwindCSS. So we want to add the dark class to the html element when dark mode is active in Ladle and we want to make sure it is not present when light mode is active.

To create the global provider we create a file at .ladle/components.tsx. Then we have to export a component called Provider of type GlobalProvider. The Provider receives the following props:

To achieve our goal we have to create a component which uses an Effect Hook which toggles the dark class whenever the theme in Ladle changes.


import type { GlobalProvider } from "@ladle/react";
import React, { useEffect } from "react";
import "tailwindcss/tailwind.css";
export const Provider: GlobalProvider = ({ children, globalState }) => {
useEffect(() => {
if (globalState.theme === "dark") {
} else {
}, [globalState.theme]);
return <div className="p-4">{children}</div>;

That's all, have fun developing components in light and dark mode.

Posted in: ladle, tailwindcss, react