Reputation: 945
I am attempting to change the color style of my header when a user scrolls the page, however, my onScroll
method doesn't even seem to be firing. Can someone please tell me why and how I can fix this? The onScroll
method is being called on the bottom TemplateWrapper
component. Also, if you have any other suggestions on how to do it differently, I'm all 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',
}}
>
About
</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
Upvotes: 1
Views: 2970
Reputation:
You need add an eventlistener in componentDidMount and store your value in state, you need to rerender your component onScroll,
componentDidMount = () => {
window.addEventListener('scroll', ()=>{
this.setState({
// your flags
});
});
};
Note: if you want to add event listener to your div, you can access to it by ref in react like this,
componentDidMount = () => {
this.listener.addEventListener('scroll', ()=>{
this.setState({
// your flags
});
});
};
render(){
return(
<div ref={(listener) => { this.listener = listener }}></div>
)
}
Upvotes: 2