javascript - Update style on scroll event in React -


i attempting change color style of header when user scrolls page, however, onscroll method doesn't seem firing. can please tell me why , how can fix this? onscroll method being called on bottom templatewrapper component. also, if have other suggestions on how differently, i'm ears! thanks!

const headerstyle = {       background: 'grey',       marginbottom: '1.45rem',       position: 'fixed',       top: 0,       left: 0,       width: '100%',       zindex: '99' }  const modheader = () => {   headerstyle.background = 'white'   console.log('scroll') }  const header = () => (    <div classname='header'     style={headerstyle}   >     <div       style={{         margin: '0 auto',         maxwidth: 1160,         padding: '1.45rem 1.0875rem',         display: 'flex',         flexdirection: 'row',         justifycontent: 'space-between'       }}     >       <h1 style={{ margin: 0 }}>         <link             to="/"             style={{               color: 'white',               textdecoration: 'none',             }}           >             gatsby         </link>       </h1>       <h2 style={{ margin: 0 }}>           <link           to="/about"           style={{             color: 'white',             textdecoration: 'none',           }}         >                   </link>       </h2>     </div>   </div> )  const templatewrapper = ({   children }) => (     <div onscroll={modheader}>       <helmet         title="gatsby default starter"         meta={[           { name: 'description', content: 'sample' },           { name: 'keywords', content: 'sample, something' },         ]}       />       <header />       <div          style={{           margin: '0 auto',           maxwidth: 960,           padding: '0px 1.0875rem 1.45rem',           paddingtop: 0,         }}       >         {children()}       </div>     </div>   )  export default templatewrapper 

you need add eventlistener in componentdidmount , store value in state, need rerender component onscroll,

componentdidmount = () => {    window.addeventlistener('scroll', ()=>{      this.setstate({        // flags       });     });    }; 

note: if want add event listener div, can access ref in react this,

componentdidmount = () => {    this.listener.addeventlistener('scroll', ()=>{      this.setstate({        // flags       });     });    }; render(){    return(         <div ref={(listener) => { this.listener = listener }}></div>     )  } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -