Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch between themes in Ant design v4 dynamically?

I'd like to implement switching between dark/light theme dynamically with Ant design v4.

It's possible to customize the theme with other CSS/LESS imports as it's written here: https://ant.design/docs/react/customize-theme#Use-dark-theme

But I'm not sure how to switch between those themes dynamically from the code. I have a variable in my React app (darkMode) which indicates if the dark theme is currently used. I have to provide correct CSS files when this variable is changed. But I can't import CSS dynamically only when some condition is fulfilled, because it's not way how the imports work.

I tried to do something messy with require like in the following code, but it's a very very bad approach and it's still not working properly (because CSS is injected but probably not withdrawn. ):

const Layout = () => {
  ...
  useEffect(() => {
    if (darkMode === true) {
      require("./App.dark.css")
    } else {
      require("./App.css")
    }
  }, [darkMode])

  return (
    <Home />
  )
}

It should be possible to switch themes somehow because it's already implemented in Ant design docs (https://ant.design/components/button/):

Theme switch in Antd docs

Do you have any idea how to do it?

Thanks!

like image 909
J V Avatar asked Mar 02 '20 15:03

J V


People also ask

How do you implement Dark mode in react?

Adding DarkMode to the App import React from "react"; import logo from "./logo. svg"; import "./App. css"; import DarkMode from "./DarkMode"; function App() { return ( <div className="App"> <header className="App-header"> <DarkMode /> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.


1 Answers

you must create 2 components

the first one :

import './App.dark.css'

const DarkApp =() =>{
   //the app container
}

and the second :

import './App.light.css'

const LightApp =() =>{
   //the app container
}

and create HOC to handle darkMode like this :

const AppLayout = () =>{
const [isDark , setIsDark] = useState(false);


return (
 <>
  {
  isDark ? 
    <DarkApp /> :
      <LightApp />
  }
 </>
 )
}
like image 181
i am davood Avatar answered Oct 14 '22 17:10

i am davood