javascript - Access <body> from React -
i'm new react , trying build standalone header component containing 'slide in sidebar'. used state apply css slide 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 job in terms of sliding sidebar, once sidebar open, lock scroll on body applying overflow:hidden <body>. since <body> outside of react, wondering how it's possible access tag? 
use document.body set styles need. make sure access document after it's ready, put code in componentwillmount. should reset styles after unmounting component in componentwillunmount.
componentwillmount() {     document.body.style.overflow = "hidden"; }  componentwillunmount() {     document.body.style.overflow = "visible"; // or restore original value }   after comment realized need set styles after opening sidebar. here notes:
- don't use 
this.stateinsetstate.setstateasynchronous, therefore should use optionalprevstateparameter access previous state object. - you use optional second parameter of 
setstatefunction , called after state updated. in function set styles of body. - you can 
bindfunction in constructor. - in constructor pass 
propsbase constructor (super(props)). - rename 
sidebarissidebaropen. more descriptive name. 
here 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>     )      
Comments
Post a Comment