DEV Community

Cover image for Dark mode with Ladle and TailwindCSS
Sebastian Sdorra
Sebastian Sdorra

Posted on • Originally published at sdorra.dev

 

Dark mode with Ladle and TailwindCSS

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:

  • children: The current story
  • globalState: The global state of Ladle, which contains the active theme
  • storyMeta: The metadata of the story, such as the name

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") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  }, [globalState.theme]);
  return <div className="p-4">{children}</div>;
};
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted

50 CLI Tools You Can't Live Without

>> Check out this classic DEV post <<