Is it possible to dynamically set the body id in React?

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?

Answer №1

After reading through the comments on your original question, it seems you've opted to make modifications directly to the body element in the browser's DOM. This approach may work well since the body element is not controlled by React and is unlikely to be altered by other code.

However, I'd like to offer some suggestions for a cleaner solution:

  • Consider using a data attribute such as

    data-display-mode="dark"
    as a target for your CSS selectors instead of relying on IDs. IDs are meant to be stable, and other tools or libraries (like UI test tools) may depend on this stability.

  • Utilize the Modal.container property to attach your Modals to the App element (the globally parent div controlled by React in your code), rather than the app-root-div in index.html. By setting the data-display-mode attribute here using React methods, you can avoid bypassing the virtual DOM.

  • Implement CSS custom properties for defining colors, and centralize all dark mode adjustments in one location. Avoid scattering your dark-mode styling rules across multiple class selectors to simplify maintenance in the long run.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of updating input values via jQuery AJAX in HTML response is currently not functioning as expected

Hello, I need some assistance. I'm encountering difficulty with jQuery in modifying HTML values that are dynamically inserted through an AJAX response. Here is the link to the JSFiddle. Below is the HTML on the page: <button id="test">test&l ...

Navigating the web page and locating the appropriate Xpath element to extract

Here is the HTML that needs to be extracted: <input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callbac ...

"Enhancing User Experience with ReactJS MUI Box: Implementing a seamless CSS transition on click events

Check out my sandbox. I've implemented a switch component using divs, but now I want to incorporate a smooth transition effect similar to this example https://codepen.io/nikkk-me/pen/abvPjeG. I tried adding the following CSS code: after: { transfo ...

The CSS ::after selector is experiencing a decrease in animation speed

There is a dropdown menu set to fade in once a link is clicked. Everything works well, the menu fades in properly. However, when clicking off and triggering a function that fades out the dropdown, the triangle on top of the box fades out slightly slower th ...

ReactJS encounters an error when a high order component throws an invalid React element

Recently, I've been delving into the concept of HOCs and decided to incorporate them into my application in order to effectively pass down authorization logic to the child components. In attempting to render a <Route /> component through the HO ...

Adjust the quantity by clicking or typing

Hey there! How's it going? I'm curious to learn how I can enable the user to manually input the quantity in the field, in addition to using the plus and minus buttons. Essentially, is there a way for the user to type in the number of items they ...

Exploring the differences between named exports/imports and imports with absolute path

Currently, I am working on developing a component library named awesome-components as an npm module. This library will include buttons, inputs, dropdowns, and other components that users can easily install in their react applications. However, I am facing ...

Creating a user authentication portal

Looking for advice on creating a basic front end HTML login. I'm new to coding and would appreciate any suggestions! Additionally, how can I link the login system to my database? ...

Having trouble with installing Material UI Icons through npm: encountering difficulties in resolving the dependency tree

---------RESOLUTION SUCCESSFUL - SOLUTION PROVIDED AT THE END OF QUESTION-------- I encountered an issue while attempting to integrate Material UI Icons into my React.js Netflix-Clone project using npm. The error message I received was as follows: PS D:&b ...

What is the method for altering font color in HTML?

Here is the section of my code that I am struggling with: <p style="font-family:'impact', color:red"> something </p> The issue I am facing is that I am unable to use both the color and the font propert ...

The placement of my footer is off and not aligned with the bottom of the page

I am struggling to make my footer align with the bottom of the page rather than sticking to the bottom of the browser window and moving along with the scroll. How can I fix this issue? The goal is to have the footer remain out of sight at the bottom of th ...

Styling using CSS is effective only when applied locally, as it does not function properly on GitHub Pages

Although I have come across similar questions to the one I am facing, none of the solutions provided seem to work for me at the moment. My CSS file loads and functions as expected when tested locally, but once I upload it to GitHub, it stops working. In my ...

The request to remove the product from the server at URL http://localhost:8000/product/[object%20Object] encountered an internal server

I'm having trouble setting up the AJAX delete method. I keep getting a 500 internal server error and despite following tutorials, I remain frustrated. Can someone please help me correct my code? This is using Laravel 5.8 and jQuery 3.3. <section ...

Incorporate a lesson featuring jQuery into your curriculum

Just starting out with jQuery and I have a form setup like this: <select name= "menus"> <option value="">--Select--</option> <option value="a">a</option> <option value="b">b</option> <option val ...

Instructions for adding an onfocus event listener to an input field in order to dynamically change the formatting of associated labels

I'm looking to change the style of my input labels to a more fancy look by implementing the .fancyclass style when using the onfocus event on the input field. I am curious to know how this can be achieved through event listeners in Javascript? ...

Select the radio button by hovering the mouse over it

Is there a way to check my radio buttons when hovering over them without having to click? I want to display photos based on the selected radio button. I attempted this using JQuery, but I am still learning and consider myself a beginner. ...

JavaScript source control tool

Is there a Java-based version of GitHub? I am interested in developing a dynamic application using HTML5 and Javascript, and had the thought of integrating Git to monitor data changes. Therefore, I am curious if there exists a JavaScript adaptation of a G ...

Retrieve an item from an array using a Select component

Is there a way to retrieve the complete object representation of an item from a list in React? Currently, when I select an item and call handleChangeSelectAuto, the original value from useState is returned instead of the entire object. How can I ensure tha ...

Tips for improving my page's performance in React/Next.js without triggering excessive re-renders

Hey there! I recently worked on enhancing a user profile editing page in my react project. The page includes a dropdown selector from the react-select library and an input text box. To manage states, I utilized zustand. Everything was running smoothly unti ...

website with a horizontal scroll-bar

Looking to create a horizontal scrolling website where the divs float to the right without specifying the container's width, as it may vary on different pages. Any suggestions? ...