4

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?

double-beep
  • 5,031
  • 17
  • 33
  • 41
tanmay
  • 51
  • 1
  • 7

1 Answers1

0

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)

  • 1
    Yeah even i think this is not the best solution.Its just the client provided me with these two css files and asked to apply a toggle option.I dont know what to do – tanmay Aug 16 '20 at 08:07
  • Ah ok, fair enough. I think the link I provided should definitely point you in the correct direction. :) – Jasper Chesselet Aug 16 '20 at 08:23