Under the Hood
Let's begin, I want to add a dark/white theme to my website what should I do?
That is how the story begins literally theme toggle on the website
So most of the websites use Tailwind CSS in React so let’s begin with that only.
Step 1
Append the theme classname to the root element of the application.
Basically, the root div element of the application should contain the classname as the dark when a theme is dark and white when a theme is white.
import React from "react";
const App = () => (
<div classname={`${theme}`}>
<div> Home </div>
</div>
);
export default App;
Step 2
Store the current theme in local storage.
Add the dark theme CSS to the UI components as shown in the code example below.
import React from "react";
const App = () => {
const theme = window.localstorage.get("theme");
// fetch theme from localstorage
return (
<div classname={`${theme}`}>
<div> <button className="dark:bg-gray-800 bg-gray-100"></button></div>
// append the dark theme and work is done
</div>
)};
export default App;
Step 3
Enable dark theme in Tailwind configuration
Go to the tailwind.config.js
file in the root directory, if not available please create one with the same name.
// append the below line or out it after purge key
darkMode: "class", // or 'media' or 'class',
This will basically instruct tailwind to append the given class CSS present in the root of the element.
Tailwind CSS will provide a manual theme or by default white theme if the ‘media’ value is provided.
Conclusion
That’s it two steps and you can theme toggle in tailwind css application, in fact in all the applications.
Below is the Github repository as the code sample, enjoy it.
Until next time, have a good day, people
Shrey
iHateReading
Top comments (5)
Can be your next topic, how to setup tailwind and how to in env file change theme. Like blue, orange, yellow. Same layout but primary color to be blue or what I write in env file and in SCSS or sass to conditionally display?
I still haven't covered multiple theme support, but I want to cover it. I am unsure, but we can do it without making many changes in the env file.
We will pass the classname corresponding to the current theme to the root of the application and add the inline CSS accordingly just like we did for dark theme
That's all?! Cool! But two things drawn my attention. Why
className={'${theme}'}
instead ofclassName={theme}
? And why a div surrounding the button tag?Using
className={theme}
will also work.'${theme}'
(with backticks) would just convert to a string, if it not already is. But the solution is not really good, because it ignores common react coding conventions like states and does not explain how the theme will be updated in local storage. On top it will not work for server-side rendering like many other solutions.I want to add inline CSS to the root of the application, so I prefer the former one.
But {theme} will also work