1

With React, what is the proper way to make functions on scroll?

For example if user scrolls 500px from the top I would like console to log something. What is the best way to do this?

0

2 Answers 2

1

You would have to use DOM to set up a scroll event listener. Take this example:

import React from 'react';

export default class App extends React.Component {

  componentDidMount() {
    document.addEventListener('scroll', this.onScroll);
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this.onScroll);
  }

  onScroll() {
    var scrollY = window.scrollY;
    if (scrollY === 500) {
        console.log(`Scrolled ${scrollY} px`);
    }
  }

  render() {
    return (
      <main>
        <div>Some content</div>
        { this.props.children }
      <main>
    );
  }
}

This code example should give you a good idea on where to take your app. I hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

0

You will likely want to subscribe to the scroll event on window.

To attach a listener, you are going to call addEventListener and pass it a function:

window.addEventListener('scroll', someFunction);

Now, as to when React comes into play, you will probably want to attach the listener in the componentDidMount hook of your top-level component:

class App extends React.Component {
  constructor() {
    super();
    this.handleScroll = this.handleScroll.bind();
  },

  handleScroll(evt) {
    const fromTop = window.scrollY;
  },

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

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

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.