Skip to content

Instantly share code, notes, and snippets.

@Vinorcola
Last active March 2, 2022 08:04
Show Gist options
  • Save Vinorcola/93f8431bb190895f5de423db25f3890f to your computer and use it in GitHub Desktop.
Save Vinorcola/93f8431bb190895f5de423db25f3890f to your computer and use it in GitHub Desktop.
React Router Anchor Scroller component

Anchor Scroller component

A component to scroll page to anchor element for React Router.

This component can be used instead of https://github.com/rafgraph/react-router-hash-link package.

The AnchorScroller component is much more simple that react-router-has-link that requires timeout and MutationObserver. This component will wait for all it's children to be rendered before triggering the useEffect method that will try to find an element in the document that match the url hash, and scroll it into view.

This component has the following advantage:

  • You don't have to replace your Link component to HashLink
  • It works out-of-the-box with useNavigate
  • It also work out-of-the-box on page load
import { ReactNode, useEffect } from "react"
import { useLocation } from "react-router-dom"
interface Props {
children: ReactNode
}
export default function AnchorScroller(props: Props) {
let location = useLocation()
useEffect(() => {
if (location.hash !== "") {
let elementId = location.hash.substring(1)
let element = document.getElementById(elementId)
if (element === null) {
return
}
element.scrollIntoView()
}
}, [location.hash])
return props.children as JSX.Element
}
export default function App() {
return (
<BrowserRouter>
<AnchorScroller>
<Routes>
{/* App content here */}
</Routes>
</AnchorScroller>
</BrowserRouter>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment