Tailwind-Styled-Component icon indicating copy to clipboard operation
Tailwind-Styled-Component copied to clipboard

Dark mode not working!

Open pol-dev-shinroo opened this issue 2 years ago • 1 comments

Because dark mode css for tailwind seemed bit messy (like i have to add "dark:" to every dark mode class i want to implement), i tried to make it cleaner by passing arrays of dark mode classes as props to my styled-components where i use dark function i created to return "dark: classname" for every classnames in the array.

Here are the example:

const dark = (props: string[]): string => {
  console.log(props);
  return props.map((s) => `dark:${s}`).join(" ");
};

export default dark;
import tw from "tailwind-styled-components";

function App() {
  const [theme, setTheme] = useState<string | null>(null);

  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  }, [theme]);

  const handleThemeSwitch = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };
  return (
    <>
        <MyBtn
          $dark={["bg-stone-200", "text-xs", "text-black", "rounded-3xl"]}
          className="bg-slate-900 p-4 text-white"
          onClick={handleThemeSwitch}
        >
          Dark Mode
        </MyBtn>
      </Grid>
    </>
  );
}

interface MyBtnProps {
  $dark?: Dark;
}

const MyBtn = tw.button<MyBtnProps>`
 ${({ $dark }) => $dark && dark($dark)}
`;

When i checked the dev-tool, i can clearly see that "dark: classname" is being added. However, the dark mode isnt working when the button is clicked.

After hours of bug-finding, i gave up.

pol-dev-shinroo avatar Jan 09 '23 18:01 pol-dev-shinroo

This might be because of tailwind not recognizing the use of the dark class names. Try adding those classes to the tailwind config safelist, so the compilers keeps them.

jahirfiquitiva avatar Apr 10 '23 19:04 jahirfiquitiva