Simple Guide to Dark Mode with Gatsby.js: gatsby-plugin-use-dark-mode
I recently finally implemented Dark Mode for this blog (try that toggle in the top right), so it seemed appropriate to publish a short walkthrough for anyone else wanting to do the same thing.
If your CSS is setup to default to light mode, but the user selects dark mode, the next time they visit your site, they will be in dark mode. However, the user will see a flash of light mode before the app is spun up and useDarkMode is called.
That's why you need use gatsby-plugin-use-dark-mode to inject noflash.js for you to prevent above issue.
The initial dark mode is queried from the system. Note: this requires a browser that supports the prefers-color-scheme: dark media query (currently only Safari Technology Preview) and a system that supports dark mode, such as macOS Mojave.
Step 1: Install Dependencies
yarn add gatsby-plugin-use-dark-mode use-dark-mode
Step 2: Add the plugin to your gatsby-config.ts
module.exports = {
plugins: [
'gatsby-plugin-use-dark-mode',
],
};
Step 3: Setup your CSS to display different views
Update your global.css with styles for dark mode and light mode
@tailwind base;
@tailwind components;
@tailwind utilities;
body.light-mode {
@apply bg-white text-gray-800;
}
body.dark-mode {
@apply bg-gray-900 text-white;
}
Step 4: Creating a Toggle
Our only task left is to build a UI component to give users the power to directly choose their theme. For the purposes of this post, we’ll use react-switch to build a simple toggle button as a starting point, but you should customize the look and feel of your toggle to fit with your site.
Create DarkModeToggle.tsx file
Here’s our toggle component:
import React from "react";
import useDarkMode from "use-dark-mode";
import Switch from "react-switch";
const DarkModeToggle = () => {
const darkMode = useDarkMode();
return (
<div className="mr-4 lg:mr-0">
<Switch
onChange={darkMode.toggle}
checked={darkMode.value}
offColor="#f5f5f5"
onColor="#333"
offHandleColor="#333"
onHandleColor="#f5f5f5"
/>
</div>
);
};
export default DarkModeToggle;
Now you can use DarkModeToggle in your site to enjoy dark mode!
You’re done!