To scroll to a specific position within an element on page load using React's useEffect hook, you can utilize the scrollTop property of the element. Here's an example of how you can achieve this:

import React, { useEffect, useRef } from 'react'; const ScrollToPosition = () => { const elementRef = useRef(null); useEffect(() => { const scrollToPosition = 200; // Desired scroll position in pixels const element = elementRef.current; if (element) { element.scrollTop = scrollToPosition; } }, []); return ( <div ref={elementRef} style={{ height: '400px', overflow: 'auto' }}> {/* Content within the scrollable element */} </div> ); }; export default ScrollToPosition;

In this example, we use the useRef hook to create a reference to the scrollable element. The useEffect hook is used to scroll to a specific position within the element when the component mounts (empty dependency array [] ensures it only runs once on mount).

Within the useEffect callback, we access the scrollable element using the elementRef.current. We then set the scrollTop property of the element to the desired scroll position in pixels (scrollToPosition in this example).

Finally, we render a scrollable <div> and assign the ref to the elementRef. The ref allows us to access the scrollable element in the useEffect hook. You can adjust the height and overflow properties of the element as per your requirements.

With this code, the scrollable element will automatically scroll to the specified position when the component is rendered.

Have questions or queries?
Get in Touch