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.state
insetstate
.setstate
asynchronous, therefore should use optionalprevstate
parameter access previous state object. - you use optional second parameter of
setstate
function , called after state updated. in function set styles of body. - you can
bind
function in constructor. - in constructor pass
props
base constructor (super(props)
). - 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
Post a Comment