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?

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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
Ah ok, fair enough. I think the link I provided should definitely point you in the correct direction. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.