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
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:
You can dynamically set the href attribute of a single
Link
based on the state value rather than conditionally rendering different style sheets. See this answer for more details: Dynamically load a stylesheet with ReactThere 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/