0

I have a div on which I've added onScroll and triggering a function on scroll event.

import React, { useRef } from 'react';

export const DemoComponent () => {
  const myref = useRef(null);
  const scrollEvent = () => {
    //do something here
    //Problem is that this event is triggering on load multiple times even when there is no scroll happening
  };
  return (
     <div onScroll={scrollEvent} ref={myref}></div>
  );
};

On load the scroll event triggers multiple times when there is no scrolling yet. Can't seem to figure out how to prevent this.

1

1 Answer 1

1

There must be something else causing that because, from the code you provided, the event only fires when the view has been scrolled. I added styling to get the scrollbar


export default class MyComponent extends Component {
scrollEvent = () => {
  console.log("renders");
  //do something here
  //Problem is that this event is triggering on load multiple times even when there is no scroll happening
};

render() {
  const style = {
    width: "100px",
    height: "100px",
    overflowY: "scroll",
  };
  const innerDiv = {
    height: "300px",
    width: "100px",
    background: "#efefef",
  };
  return (
    <div style={style} onScroll={this.scrollEvent}>
      <div style={innerDiv} />
    </div>
  );
}
}
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.