Skip to content

Instantly share code, notes, and snippets.

@niikkiin
Last active October 22, 2020 16:03
Show Gist options
  • Save niikkiin/66893ce28fc3d760a59ec6389206ac73 to your computer and use it in GitHub Desktop.
Save niikkiin/66893ce28fc3d760a59ec6389206ac73 to your computer and use it in GitHub Desktop.
Creating Theming on React using Tailwind
//App.js
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import "./assets/main.css";
import Home from "./pages/Home";
import ThemeContext from "./utilities/ThemeContext";
function App() {
return (
<ThemeContext>
<BrowserRouter>
<Switch>
<Route path='/' exact component={Home} />
</Switch>
</BrowserRouter>
</ThemeContext>
);
}
export default App;
import React from "react";
import { ThemeContext } from "context/ThemeContext";
const Home = () => {
const { theme, setTheme } = React.useContext(ThemeContext);
const changeTheme = (event) => {
setTheme(event.target.value);
};
return (
<div className="h-screen">
<div className="text-center w-full text-2xl ">
Theme Changer
</div>
<div className="flex text-center my-8">
<div className="mx-auto">
<button
onClick={changeTheme}
value="light"
className="px-2 py-1 mr-1 rounded bg-white"
>
Light
</button>
<button
onClick={changeTheme}
value="dark"
className="px-2 py-1 ml-1 rounded bg-black text-white"
>
Dark
</button>
</div>
</div>
<div
className={`w-64 h-64 flex items-center justify-center bg-${theme}-400`}
>
Theme
</div>
</div>
);
};
export default Home;
//tailwind.js
module.exports = {
plugins: [
...
],
...
theme: {
extend: {
colors: {
dark: {
100: "#6d706f",
200: "#20c991",
300: "#ff1f4f",
400: "#dae0de",
500: "#ffffff",
},
},
},
},
};
//ThemeContext.js
import React, { useEffect } from "react";
import { useCallback } from "react";
export const ThemeContext = React.createContext();
export default ({ children }) => {
const localStorageTheme = localStorage.getItem("theme");
const [theme, setTheme] = React.useState(localStorageTheme);
// window.onload = checkTheme();
const checkTheme = useCallback(() => {
if (theme === "dark") {
localStorage.setItem("theme", "dark");
} else if (theme === "default") {
localStorage.setItem("theme", "default");
} else if (theme === "light") {
localStorage.setItem("theme", "light");
} else {
localStorage.setItem("theme", "default");
}
}, [theme]);
const defaultContext = {
theme,
setTheme,
};
// console.log(localStorageTheme);
useEffect(() => {
checkTheme();
}, [checkTheme]);
return (
<ThemeContext.Provider value={defaultContext}>
{children}
</ThemeContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment