0

I come from the Ember world so apologies if this question is very basic (I'm sure it is). I have a component which sets the state "scrollPosition" whenever the window is scrolled. I would like to define a new state property, "isScrolledToTop", which is equal to true when "scrollPosition" is 0.

In Ember I would have simple defined a new property and checked the condition when scrollPosition changed. Not quite sure how to do this in React. I was thinking of using "componentDidUpdate", but pretty sure this is not the right approach. Thanks for the help in advance!

Nicholas Haley
  • 3,558
  • 3
  • 29
  • 50
  • Possible duplicate of [Update style of a component onScroll in React.js](http://stackoverflow.com/questions/29725828/update-style-of-a-component-onscroll-in-react-js) – David Gomez Aug 13 '16 at 20:53
  • Thanks I saw this earlier. This was great for learning how to add event listeners and update one state. What I'm interesting in now is more generally, how can I update one state property when another changes – Nicholas Haley Aug 13 '16 at 20:59
  • Maybe this isn't the answer you're looking for, but couldn't you set the second state variable in the same function that updates the scrollPosition state? – azium Aug 13 '16 at 21:35

1 Answers1

0

If you're asking "how can I fire some event once the user scrolls to the top of the page" then the answer is to do that in the onscroll event callback.

If you want to render something differently (e.g. a full-size header) when the scroll position is at the top of the page, then the logic would go in the render() method of your component. Something like:

render() {
  if (this.state.scrollPosition === 0) {
    // do something specific to this scenario
  }
  return ...
}

This part of the docs suggests not putting 'computed data' in state, which is what isScrolledToTop is.

As an FYI, if you're tracking the scroll position, the window object keeps this in its 'state' for you, available at window.scrollY - you don't need to duplicate this into your component's state.

David Gilbertson
  • 4,219
  • 1
  • 26
  • 32