Search code examples
cssreactjstoggle

How to change the import of a CSS file in React App with a toggle button with useState


Is there a way to change the import of a CSS file in React App? For instance, having a light and dark mode and allowing the user toggle between them.

Attempted this but it didn't work:

`const [useStyle1, setUseStyle1] = useState(true);

const toggleStyle = () => {
  setUseStyle1(!useStyle1);
};

      {useStyle1 ? (
        <link rel="stylesheet" type="text/css" href="./App.css" />
      ) : (
        <link rel="stylesheet" type="text/css" href="./App2.css" />
      )}
      <h1>Hello, World!</h1>
      <button onClick={toggleStyle}>Toggle Style</button>`

Solution

  • You can dynamically set the href attribute of a single Linkbased on the state value rather than conditionally rendering different style sheets. See this answer for more details: Dynamically load a stylesheet with React

    There are also many other ways to dynamically set light/dark mode styles without conditionally loading style sheets such as CSS modules, CSS variables and data attributes, and lightweight libraries like classnames.

    Here are a few alternative approaches:

    https://usehooks.com/useTheme/

    https://blog.logrocket.com/dark-mode-react-in-depth-guide/

    https://css-tricks.com/easy-dark-mode-and-multiple-color-themes-in-react/