Darren
Darren

Reputation: 2290

window.addEventListener not updating state on route change when scrollY is not 0

I am adding class to a header via setState using addEventListener in componentDidMount. The state of scrolling is set to false at 0 of scrollY and upon scroll, the state is updated to true and a class is added.

As an example

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
  window.removeEventListener('scroll', this.handleScroll);
}

handleScroll = () => {
  if (window.scrollY === 0 && this.state.scrolling === true) {
    this.setState({ scrolling: false });
  } else if (window.scrollY !== 0 && this.state.scrolling !== true) {
    this.setState({ scrolling: true });
  }
};

within a GatsbyJS layout. It works perfectly between pages and templates when the user is returned to the top of the page.

However, on some occasions for example the route change via a modal or the user hits back on the browser the action is keep the previous scrollY position.

In this circumstance scrollY is not 0 but the state of scrolling is still showing false. I imagine this is because even though scrollY is showing the actual position, state scrolling is initially false until the user scrolls. This is portrayed in the console

How can I ensure that on route change, the state scrolling is updated to true if scrollY is not 0?

Upvotes: 0

Views: 179

Answers (1)

coreyward
coreyward

Reputation: 80090

You should run your handleScroll method once upon instantiation to capture the initial state. Right now you're relying on the scroll position being at the very top, but as you've found, going back in history results in a different initial state.

componentDidMount() {
  window.addEventListener('scroll', this.handleScroll);
  this.handleScroll();
}

Upvotes: 1

Related Questions