9

I'm new to React and I am trying to build a standalone Header component containing a 'slide in sidebar'. I used state to apply CSS to slide the sidebar in/out:

constructor() {
super();
  this.state = {
    sideBar: false
  }
}
handleSidebar() {
  this.setState({
    sideBar: !this.state.sideBar
  });
}
render() {
return(
  <header>
   <ul style={this.state.sideBar ? {'transform': 'translateX(0%)'} : null}></ul>
   <button onClick={this.handleSidebar.bind(this)}></button>
  </header>
)

This does the job in terms of sliding the sidebar, but once the sidebar is open, I would like to lock scroll on body by applying overflow:hidden to the <body>. However since <body> is outside of React, I was wondering how it's possible to access the tag?

Link to Codepen

2 Answers 2

12

Use document.body to set the styles you need. Make sure you access document after it's ready, so put the code in componentWillMount. You should reset the styles after unmounting the component in componentWillUnmount.

componentWillMount() {
    document.body.style.overflow = "hidden";
}

componentWillUnmount() {
    document.body.style.overflow = "visible"; // or restore the original value
}

After your comment I realized that you need to set the styles after opening the sidebar. Here some notes:

  1. Don't use this.state in setState. setState is asynchronous, therefore you should use the optional prevState parameter to access the previous state object.
  2. You could use the optional second parameter of setState which is a function and is called after the state is updated. In this function you could set the styles of the body.
  3. You can bind the function in the constructor.
  4. In the constructor pass the props to the base constructor (super(props)).
  5. Rename sideBar to isSideBarOpen. It is a more descriptive name.

Here is the final code:

constructor(props) {
    super(props);
    this.state = {
        isSideBarOpen: false
    };
    this.toggleSideBar.bind(this);
}

updateBodyStyles() {
    if (this.state.isSideBarOpen) {
        document.body.style.overflow = "hidden";
    } else {
        document.body.style.overflow = "visible";
    }
}

toggleSideBar() {
    this.setState((prevState) => {
        return { isSideBarOpen: !prevState.isSideBarOpen }
    }, this.updateBodyStyles);
}

render() {
    return (
       <header>
            <ul style={this.state.isSideBarOpen? {'transform': 'translateX(0%)'} : null}></ul>
            <button onClick={this.toggleSideBar}></button>
       </header>
    )
4
  • Hey thanks Dávid, I tried adding the styles to body once the component WillMount, but since the <Header> component is always present in my app, it just locks the scroll on body. Does it mean I should change the structure of the App? Perhaps adding the sidebar as an another component outside of the <Header>? Sep 10, 2017 at 17:56
  • Thanks for the detail answer! I was getting an error that updateBodyStyles is not defined, so I changed it to this.updateBodyStyles. Sep 10, 2017 at 19:26
  • Happy to help! Thanks for the note, I fixed the answer. Sep 10, 2017 at 19:43
  • document.body.style.overflow have no effect on the actual value when checking it in dev tools.. Not sure if its some weird logic in my specific project or not
    – Blue Bot
    Sep 9, 2021 at 15:32
0

A solution can be inserting a overlay with the sidebar too.

This quick example is just to give you an idea. you can style it as you wish.

// style
.navOwerflow {
   display: none;
}
.navOwerflow.open {
   position: absolute;
   width: 100%;
   height: 1000px; // get this height from window
   z-index: 2;
   opacity: 0.9;
   background-color: rgba(0,0,0,1);
}

 // component
 <header className="header">
        <div className={`navOwerflow ${(this.state.open && 'open')}`}></div>
        <div className="navContainer">
           ...
        </div>
 ...
 </header>
1
  • Thanks, fair point. I added the overlay & changed the burger menu to 'X' upon click, however I still can't figure out how to lock the scroll on body. Sep 10, 2017 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.