simple react hooks that makes theming your app easier and straightforward.
copy useTheming.js and paste it on your project folder, then initialize it.
import React from 'react';
import useTheming from './hooks/useTheming';
const App = () => {
// You can just straightforward call the useTheming hooks like below.
useTheming();
return (
//...
);
};
return App;
The useTheming()
functions has two return values:
theme
- {'light'|'dark'} your current theme.handleThemeChange()
- a function to change the current theme. Rename it as you wish.
So, if you want to get the current theme of your app, you can just call the hooks and use its first return value.
const App = () => {
const [theme] = useTheming();
return (
<h1>{theme}</h1>
);
};
const App = () => {
const [theme, changeTheme] = useTheming();
const handleOnClick = () => {
const newTheme = theme === 'dark' ? 'light' : 'dark';
changeTheme(newTheme);
};
return (
<React.Fragment>
<h1>{theme}</h1>
<button onClick={handleOnClick}>
Change theme
</button>
</React.Fragment>
);
};
How about the theming itself? How do I make my app look different if the theme is dark and vice-versa?
You have to create CSS variables. The dark theme will be wrapped inside a [data-theme="dark"]
block, like this:
:root {
--title-color: #000;
}
[data-theme="dark"] {
--title-color: #FFF;
}
Above, if the current theme is light
, the --title-color
variable gonna have a value of #000
.
If the theme is set to dark
, the variable will have a value of #FFF
.