1

I need to add or remove class on element if page is scrolled in react I wrote such a code to track page scroll:

export default class TestComponenet extends React.Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {
      scrolled: false
    }
  }

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

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

  handleScroll(event) {
    this.setState({srolled: true});
  };

  render() {
    return (
      <div className ={scrolled ? 'scrolling' : ''}></div>
    );
  }
}

but I can only track scroll but I cannot toggle class dynamically.

3
  • Your question is very vague. Do you think you could elaborate a bit, and also maybe show your entire component? Commented Jun 25, 2018 at 18:13
  • added............................ Commented Jun 25, 2018 at 18:17
  • this.state.scrolled Commented Jun 25, 2018 at 18:24

1 Answer 1

2

There is no real "scroll state" in the browser. You get an event when the user scrolled, and then it's over. You could keep a timeout that will set it to not scrolling if the user hasn't scrolled in a while:

Example

class App extends React.Component {
  state = {
    scrolled: false
  };

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

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

  handleScroll = event => {
    this.setState({ scrolled: true });

    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.setState({ scrolled: false });
    }, 200);
  };

  render() {
    const { scrolled } = this.state;

    return (
      <div
        className={scrolled ? "scrolling" : ""}
        style={{
          width: 200,
          height: 1000,
          backgroundColor: scrolled ? "blue" : "red"
        }}
      />
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.