DEV Community

IHesamI
IHesamI

Posted on • Edited on

Don't use State for Theme

Greetings, In this article I will show a simple technique for changing and setting multiple themes in a React application. To begin, we will need to create a file named theme.js and input the following code into the file:


let rootNode;

export function initRoot(root) {
    rootNode = root;
}
export function changeTheme() {
    const rootTheme = rootNode.dataset?.theme
    rootNode.dataset.theme = rootTheme == 'dark'? 'light' : 'dark';
}
Enter fullscreen mode Exit fullscreen mode

The root element of the tree is declared in the first line, and the initRoot function is tasked with initializing this element. This function should be invoked at the highest level of the react tree in main.js, with a parameter of the root node.

The changeTheme function is responsible for altering the theme, and can be called whenever a button or click handler is required.
something like this :

import { changeTheme } from "./theme";

export default function ThemeChanger(/* your props */) {
    return (
        <button onClick={changeTheme}>{/*your title*/}</button>
    )
}
Enter fullscreen mode Exit fullscreen mode

Update the properties within the css file to customize them for various themes.

:root {
  --background-color: #fff;
  --text-color: #000;
}

#root[data-theme=dark] {
  --background-color: #000;
  --text-color: #fff;

}

.app-container {
  color: var(--text-color);
  background-color: var(--background-color);
}
Enter fullscreen mode Exit fullscreen mode

Every desired color that you intend to utilize must be declared as a property and possess a corresponding equivalent in the dark theme mode. Subsequently, employ the var function in CSS to make use of these colors.

It is crucial to refrain from altering the DOM since React utilizes a virtual DOM. However, this method is simple and does not impact the actual DOM.

Thank you for taking the time to read this. I hope you found this post useful. Please feel free to share your thoughts in the comments section.

Top comments (0)