I'm currently working on implementing a dark mode feature in my app.
The plan is to insert the following code into the root element:
<div id="dark">
Afterwards, add the following CSS:
#dark {
background-color: #1A1A2E;
}
Subsequently, customize each DOM element using classes in CSS. For instance, let's focus on cards:
#dark .card-body {
background-color: #16213E !important;;
}
#dark .card-header {
background-color: #0F3460 !important;
}
This setup works perfectly fine.
However, when it comes to Modals, the dark mode doesn't seem to apply. This could be because Modals are not initially rendered, causing the dark style not to take effect.
A workaround that worked was adding id="dark" to each modal:
#dark .modal-header {
background-color: #0F3460 !important;
}
#dark .modal-body {
background-color: #16213E !important;;
}
#dark .modal-footer {
background-color: #16213E !important;;
}
<Modal
// dark doesn't get applied automatically for modals because apparently modals are not rendered in the beginning
id="dark"
isOpen={this.state.isModalOpen}
toggle={this.toggleModal}
>
<div className="modal-header">
Nevertheless, applying this manually to every single modal can be tedious.
A solution suggested here:
The Modal should be within an element with id="dark". Since the script loads right below the script tag and you're assigning 'dark' id to a div tag where the modal isn't nested, the CSS selector won't target it. So, assign the id="dark" to the body tag instead.
This resolves the issue with modals.
However, the dilemma lies in how I control the id in the root component in my initial dark mode implementation like this:
// Root component
<div id={this.state.should_enable_dark_mode ? "dark" : "default"}>
And the should_enable_dark_mode
is handled as follows:
manageDarkMode() {
window.addEventListener("storage", () => {
console.log("change to local storage!");
let should_enable_dark_mode = localStorage.darkMode == "true";
this.setState({
should_enable_dark_mode,
});
});
}
The issue with the aforementioned solution is that I couldn't figure out how to manipulate the body tag from the React app. Plus, I'm unsure if it's advisable to do so.
What do you suggest I should do?