How to create a simple dark mode selector in React

To create a dark mode in React, first of all, add the data-theme property to index.html.

html
<!DOCTYPE html>
<html lang="en" data-theme='🔵'>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <meta name="description" content="I am Erik, an engineer from Barcelona. I code and share what I am learning.">
    <meta name="twitter:image" content="https://erikmartinjordan.com/TwitterCard.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>Erik Martín Jordán</title>
  </head>
  <body>
  </body>
</html>

Then, create a new component to switch between dark and light mode. It will be the ThemeSelector.js component:

jsx
import React, { useState } from 'react';
import '../Styles/ThemeSelector.css';

const ThemeSelector = () => {
    
    const [theme, setTheme] = useState('🔵');
    const colors = ['⚪', '🔵'];
    
    const handleTheme = () => {
      
      // Getting new color from colors array
      const newColor = colors[(colors.indexOf(theme) + 1) % colors.length];
        
      // Setting attribute in the document    
      document.documentElement.setAttribute('data-theme', newColor);
        
      // Setting new state
      setTheme( newColor ); 

    }
    
    return <div className = 'Theme-Selector' onClick = { () => handleTheme() }>
                {theme === '🔵' && <div className = '🔵'>🔵</div>}
                {theme === '⚪' && <div className = '⚪'>⚪</div>}
           </div>;
    
}

export default ThemeSelector;

By clicking on the .Theme-Selector, the data-theme attribute will switch between dark (🔵) and light (⚪) themes.

Finally, modify index.css:

css
html[data-theme = '🔵']{
    --bgColor: #243b55;
    --textColor: white;
    --linkColor: white;
}
html[data-theme = '⚪']{
    --bgColor: #f4f8fb;
    --textColor: #1f1f1f;
    --linkColor: #1f1f1f;   
}
body {
    background: var(--bgColor);
    color: var(--textColor);
}
a{
    color: var(--linkColor);
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.