Scrolling to an Anchor in React When Your Elements Are Rendered Asynchronously

Eric Cobb
1 min readMay 14, 2021

--

ZolTrain supports deep linking, and recently I had the requirement of deep linking to a specific element partway down a page. With static HTML this is simple, but our App asynchronously loads data from the API before rendering it.

This means that when a page first loads, it doesn’t actually have the HTML elements with id attributes required to make anchor links work. Instead, they are rendered a few milliseconds later once the API request has completed.

We solved this with a simple hook:

This hook uses React’s useEffect. It reads the current location from react-router with useLocation. Because useEffect has no dependencies, it runs on every render. To prevent repeatedly scrolling every time the app renders, we use a ref to track whether we have already scrolled.

Lastly, you could tweak the hook above so that it will run again if the hash changes. To do this, add another ref to track the hash itself:

--

--

Eric Cobb

Full-Stack Software Developer and Entrepreneur in Denver, Colorado. Twitter @ericdcobb