Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active July 17, 2021 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save o-az/cdcb4cb45dff09ea0c0e72811a7166a6 to your computer and use it in GitHub Desktop.
Save o-az/cdcb4cb45dff09ea0c0e72811a7166a6 to your computer and use it in GitHub Desktop.
React Theme Switch Using CSS
import * as React from 'react';
import ReactDOM from 'react-dom';
import './theme.css'
export enum Icon {
DARK = '🌘',
LIGHT = '🌦'
}
export enum Theme {
DARK = "dark",
LIGHT = "light",
}
const updateFavicon = (updated: string) => {
const favicon = document.querySelector<HTMLLinkElement>("#favicon");
return favicon ? favicon.href = `/path/to/assets/${updated}.svg` : '';
}
const Toggle = (props: any) => {
const [theme, setTheme] = React.useState<string>(Theme.DARK);
const nextTheme = theme === Theme.LIGHT ? Theme.DARK : Theme.LIGHT;
React.useEffect(() => {
document.body.dataset.theme = theme;
updateFavicon(Theme.DARK);
}, [theme]);
const updateTheme = () => {
setTheme(nextTheme)
updateFavicon(Theme.DARK)
}
return (
<button onClick={updateTheme}>
<>{theme === 'dark' ? Icon.DARK : Icon.LIGHT}</>
</button>
)
}
const App = () => <><Toggle/></>;
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
body[data-theme="dark"] {
--bg: hsl(220deg 26% 14%);
--pColor: hsl(214deg 20% 69%);
--h1Color: hsl(0deg 0% 99%);
--aColor: hsl(214deg 20% 69%);
--aHoverColor: hsl(0deg 0% 99%);
--inputColor: hsl(0deg 0% 99%);
}
body[data-theme="light"] {
--bg: hsl(0deg 0% 99%);
--pColor: hsl(220deg 27% 28%);
--h1Color: hsl(220deg 26% 14%);
--aColor: hsl(220deg 27% 28%);
--aHoverColor: hsl(220deg 26% 14%);
--inputColor: hsl(0deg 0% 0% / 10%);
}
body {
font-family: proxima-nova, sans-serif;
display: flex;
justify-content: center;
background: var(--bg);
color: var(--text-color);
margin: 0;
padding: 0;
}
/* Remove ugly scrollbar on desktop */
body::-webkit-scrollbar {
width: 0.25rem;
}
body::-webkit-scrollbar-track {
background: rgb(9, 31, 45);
}
body::-webkit-scrollbar-thumb {
background: #000000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment