Adding Dark mode to my pwa (tailwind)
Once again I have changed the majority of the styling on my website to make use of another feature of the modern browser. This time I will be adding (as you can probably tell from the title) dark mode to this pwa app.
Getting Started
For this article the main thing you have to do, when starting is change a class in your tailwind.config.js
and here is what you have to change:
module.exports = {
...
darkMode: 'media', // or 'class' or 'false'
...
}
Once this is added, your are then able to go into your HTML and start adding the dark:
to your class or className if your are using jsx templates.
Adding it to the HTML
So, go to your HTML file, or the .js / .ts file that contains your react component. Then you want to set your current style to what it will look like in light mode. So, setting the text to black and the background to a light colour.
Then when adding the dark:
class to your element you can change things like the text colour and background just prefixed with that class.
Here is an example from my website and you should be able to see how it works:
<div className="block dark:bg-gray-800 -mt-3 w-full">
<h2 className="block w-full font-serif text-3xl text-yellow-900 dark:text-yellow-400 my-2 mx-5"><b>A Develop(ing)(er) Blog...</b></h2>
<div className="bg-clip-text bg-gradient-to-b from-purple-400 via-blue-400 to-indigo-400 p-10 grid grid-cols-1 sm:grid-cols-1 md:grid-cols-1 lg:grid-cols-1 xl:grid-cols-3 gap-5 text-xl sm:text-xl md:text-2xl lg:text-3xl xl:text-4xl">
{posts.map((item) => (
<BlogListItem key={item.slug} {...item} />
))}
</div>
</div>
On the outermost div, I only give it a background when it is in dark mode. By applying the dark:
key word before setting the bg-colour using the tailwind syntax.
Another example from this is:
<h2 className="text-yellow-900 dark:text-yellow-400"><b>A Develop(ing)(er) Blog...</b></h2>
As you can see in light mode the text will be set to text-yellow-900
. And when the device is in dark mode it will be set to text-yellow-400
.
If you have any questions or need help implementing it just drop me a message through email and I will take a look and see if I can help.
Thank you for reading!