umma.dev

Dark and Light Mode in React

Dark mode has become a popular option when it comes to picking a theme for a website. Here I discuss my findings of Dark Mode and implmenting them wit React and Tailwind, and briefly look at alternative options to Tailwind.

Detect if the User's Browser is Set to Dark Mode

window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(prefersDark)

Dark Mode Design Considerations

Contrast

According to the WAGS’s AA standard WCAG’s AA standard webpages should have a contrast ratio of at least 4.5:1 between text and images of text. This means that in dark mode the surfaces must be dark enough to display white text.

Colours

It is safer to stay away from a black (#000) background and use black to contrast certain parts of a dark theme.

Ususally more saturated tones will cause the user to strain their eyes in comparsion to lighter tones.

Google Material Design recommends using a contrast ratio of 15.8:1 between text and background. Colour ratios can be tested with this tool.

Options Available for Implementing Dark Mode in React

  • Tailwind CSS
  • Material-UI Themes
  • Plain CSS/SASS/CSS
  • NPM packages such as dark-mode

Tailwind

Setting Up Tailwind

yarn add tailwindcss postcss-cli autoprefixer -D

npx tailwind init tailwind.js --full

touch postcss.config.js

In postcss file…

const tailwindcss = require('tailwindcss')
module.exports = {
    plugins: [tailwindcss('./tailwind.js'), require('autoprefixer')],
}

Add a styles folder and create a index.css file

In the index.css file…

@tailwind base;

@tailwind components;

@tailwind utilities;

Change the following in package.json

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:styles": "postcss  src/styles/index.css -o src/styles/tailwind.css",
    "prebuild": "yarn build:styles",
    "prestart": "yarn build:styles"
}

Dark/Light Theme in Tailwind

There are two ways to implement dark mode in Tailwind. One is to use the plugin Tailwind CSS Dark Mode and the other is so create a theme yourself.

Creating a Dark Theme in Tailwind

In the config file find screens and add

module.exports = {
  theme: {
    extend: {
      screens: {
        dark: { raw: '(prefers-color-scheme: dark)' },
      },
    },
  },
}

This will enable Tailwind to identify whether the user’s browser preference is set to dark mode.

The elements in the component can then specify styles for dark mode.

<div class="bg-green dark-mode:bg-black"></div>