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?

link codepen

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:

  1. don't use this.state in setstate. setstate asynchronous, therefore should use optional prevstate parameter access previous state object.
  2. you use optional second parameter of setstate function , called after state updated. in function set styles of body.
  3. you can bind function in constructor.
  4. in constructor pass props base constructor (super(props)).
  5. rename sidebar issidebaropen. 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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -