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:
- Don't use
this.state
in setState
. setState
is asynchronous, therefore you should use the optional prevState
parameter to access the previous state object.
- 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.
- You can
bind
the function in the constructor.
- In the constructor pass the
props
to the base constructor (super(props)
).
- 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>
)