Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React how to get the scroll amount on an element?

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 this question, I usually see results that show how to get the scroll amount on the window.

However I’m looking for the scroll amount on a component that I have created called <Timeline/>, not the window.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is what my component looks like on the console:

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading