skip to Main Content

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>`

2

Answers


  1. You can’t change the path of an import. But you can import both of the CSS files and create a new state variable with the initial value of light/dark mode (whatever you want for the first time). Then, on a button click or something, you can change that variable to the new CSS.

    Here’s an example:

    import { useState } from 'react'
    import lightCSS from './light-mode.css'
    import darkCSS from './dark-mode.css'
    
    export default function Component() {
      const [mode, setMode] = useState('light')
      const [styles, setStyles] = useState(lightCSS)
    
      const toggleMode = () => {
        setStyles(mode === 'light' ? darkCSS : lightCSS)
        setMode(mode === 'light' ? 'dark' : 'light')
      }
    
      return (
        <button class={styles.button} onClick={toggleMode}>Toggle Mode</button>
      )
    }
    
    Login or Signup to reply.
  2. 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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search