Home > Back-end >  React how to get the scroll amount on an element?
React how to get the scroll amount on an element?

Time:10-15

I've made a react application where I have a component that has a scroll bar at the bottom of it. It's a horizontal scroll bar and I want to get how much the user has scrolled in terms of x position.

When I look it up on internet, such as enter image description here

When a user scrolls on it, I need to see where exactly the current visible part of it stands so I can make calculations with it.

On a given time only a certain part of the div is visible (As big as the window) and the rest is hidden on both left and right. I want to see, when scrolled, how far the user has scrolled and how much is invisible on the left side of the screen.

How can I get that?

CodePudding user response:

This is one of those situations where you use a ref. Then you can get the scrollLeft from the element. Here's a basic example:

const { useRef } = React;

const Example = () => {
    const elementRef = useRef(null);
    const showScroll = () => {
        console.log(`scrollLeft = ${elementRef.current.scrollLeft}`);
    };
    return (
        <div>
            <input type="button" value="Show Scroll" onClick={showScroll} />
            <div className="container" ref={elementRef}>
                <div className="wide" />
            </div>
        </div>
    );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
.container {
    border: 1px solid black;
    overflow: auto;
}
.wide {
    width: 400vw;
    height: 50px;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

CodePudding user response:

If you want to access the scrolling position during an event handler, then simply using a ref and element.scrollLeft is the correct way.

But note that this will not trigger a rerender, so it will not work if you want to use the scrolling position to determine what/how to render.

In such cases it depends on what you are trying to do. If for instance you want to use the scrolling position in order to position another element, I would first try doing it with CSS only, as it's going to be a lot more efficient. Otherwise you can use an event listener on the scroll event.

const [scrollPosition, scrollPosition] = React.useState(0);
const handleScroll = () => {
    setScrollPosition(elementRef.current.scrollLeft);
}

return (
    <div onScroll={handleScroll} ref={elementRef}>
        [...]
    </div>
); 
  • Related