Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  150] [ 4]  / answers: 1 / hits: 24361  / 7 Years ago, sun, september 10, 2017, 12:00:00

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


More From » html

 Answers
31

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>
)

[#56528] Thursday, September 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sophiak

Total Points: 242
Total Questions: 90
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;