@md5dalton
Posted
Hello Azhar.
Here's a component I've reused whenever I needed the functionality of toggling Dark/Light theme:
import React, { useState, useEffect } from 'react'
export default () => {
const defaultTheme = "light"
const altTheme = "dark"
const getTheme = () => localStorage.getItem("theme")
const [ theme, setTheme ] = useState(getTheme())
const toggleTheme = () => {
const theme = getTheme()
let newTheme = theme !== defaultTheme ? defaultTheme : altTheme
if (!theme) newTheme = altTheme
localStorage.setItem("theme", newTheme)
setTheme(newTheme)
}
useEffect(() => {
document.body.classList.remove(defaultTheme, altTheme)
document.body.classList.add(theme || defaultTheme)
})
return (
<div className="theme-toggler">
<label htmlFor="theme">{theme || defaultTheme} mode</label>
<input type="checkbox" id="theme" checked={theme === altTheme ? true : false} onChange={toggleTheme} />
</div>
)
}
You can always modify the JSX to your likingπ
Marked as helpful
@azhar1038
Posted
@md5dalton Thanks!
If the theme changes after component is loaded, won't there be any flickering of screen?
@md5dalton
Posted
@azhar1038 you're welcome.
No because in front-end Dark/Light mode theme implementations, the white background flash happens on initial app load and not when a component is rendered.
I'll leave a link here to a challenge I completed so you can see it in action:
@azhar1038
Posted
@md5dalton But I do see flash in live preview π
I opened your site, switched to dark mode and then upon reopening I see cards starts light and then go dark.
Maybe it is because of transitions, I am not sure.
(BTW, I checked in my 5 year old phone)