I want to apply an option where user can switch between dark mode and light mode in the application.
<link rel="stylesheet" href="../src/cssf/light.css">
<link rel="stylesheet" href="../src/cssf/dark.css">
I have two sheets for the whole website.
<label class="form-check-label" id="dark">
<input type="radio" class="form-check-input" checked name="theme"><label>Dark</label>
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label" id="light">
<input type="radio" class="form-check-input" name="theme"><label>Light</label>
</label>
I have given the option but what do i have to do to switch between the two css files?
import React, { useEffect, useState } from "react";
import "./cssf/style.css";
import logo from "./cssf/logo-sm.png";
function App() {
const [ stylePath, setStylePath ] = useState("./cssf/dark-theme.css");
const handleButtonClick = () => {
setStylePath("./cssf/light-theme.css");
}
useEffect(() => {
var head = document.head;
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = stylePath;
head.appendChild(link);
return () => { head.removeChild(link); }
}, [stylePath]);
I used this method and it is updating the link tag perfectly in the head but without importing it to my app using import “../cssf/sheername.css” it is of no use.How can i solve it?
Advertisement
Answer
that’s quite an interesting issue.
For dynamically importing css files into react I’d check this thread: here
However I don’t think this is the best solution, as it is potentially very hard to maintain and not very DRY.
I would rather have 1 css file that looks at the class on body and changes css colors based on that (assuming you don’t change layout, only colors)