Search code examples
javascriptreactjstoggle

React Toggle Body Class with button


I'm still learning React but I'm having an issue toggling a body class with a button in the menu.

const toggleSideMenu = event => {
        // toggle class on click
        //Below is not correct
        event.getElementsByTagName('body').classList.toggle('sb-sidenav-toggled');
      };`


<button onClick={toggleSideMenu} id="sidebarToggle" href="#!"><i className="fas fa-bars"></i></button>

I'm used to doing this easily in jQuery but it's not recommended to use jQuery in React because of the dom. I would appreciate any suggestions.

Thanks so much!


Solution

  • getElementsByTagName() is method of Document or Element, not react event.

    What you need to do, is to look for body inside document.

    Also getElementsByTagName(), returns HTMLCollection (many elements), so you need to grab first one (usually there is only one body element on page)

    document.getElementsByTagName('body')[0].classList.toggle('sb-sidenav-toggled');
    

    There is also shortcut for body element document.body, so it can be also written as:

    document.body.classList.toggle('sb-sidenav-toggled');