Search code examples
htmlreactjsclassname

Add a class to the HTML <body> tag with React?


I'm making a modal in my React project that requires a class to be added to the body when the modal is open and removed when it is closed.

I could do this the old jQuery way by running some vanilla JavaScript which adds / removes a class, however this doesn't feel like the normal React philosophy.

Should I instead setState on my top level component to say whether the modal is open or closed? Even if I did this, as it's rendered into the div on the page it's still a side-effect to edit the body element, so is there any benefit for this extra wiring?


Solution

  • TL;DR use document.body.classList.add and document.body.classList.remove

    I would have two functions that toggle a piece of state to show/hide the modal within your outer component.

    Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below:

    openModal = (event) => {
      document.body.classList.add('modal-open');
      this.setState({ showModal: true });
    }
    hideModal = (event) => {
      document.body.classList.remove('modal-open');
      this.setState({ showModal: false });
    }