React Router Hash Link provides essential hash fragment scrolling functionality for applications built with React Router v4/5/6. Addressing a long-standing limitation in native React Router's `<Link>` component, this library ensures that navigation to URLs containing hash fragments (e.g., `/path#section-id`) correctly scrolls the viewport to the corresponding HTML element. It is particularly robust as it supports scrolling to elements that might be rendered asynchronously, which is common in data-driven React applications. The current stable version is 2.4.3, with a release cadence that has seen several minor updates, indicating active maintenance. Key differentiators include the ability to specify `smooth` scrolling behavior, a flexible `scroll` prop for custom scrolling logic (e.g., with offsets), and an `elementId` prop offering an alternative to hash fragments. It requires React Router's `BrowserRouter` for proper operation and ships with both `<HashLink>` and `<NavHashLink>` components, mirroring `react-router-dom`'s `Link` and `NavLink`.
npm install react-router-hash-linkVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic usage of `HashLink` within a `BrowserRouter` context, showing how to navigate to and scroll smoothly or instantly to specific sections identified by hash fragments, including scrolling to the top of the page.
Review the 'Custom Link' section in the documentation for v2.0.0+ to adapt your custom link implementations, particularly regarding ref forwarding.
Ensure your application is wrapped within a `<BrowserRouter>` component from `react-router-dom`.
For broader browser compatibility, consider installing a browser polyfill for smooth scrolling, such as `iamdustan/smoothscroll`.
Use distinct hash fragment names (e.g., `#my-section`) for specific elements you wish to scroll to, reserving `#` or `#top` for top-of-page navigation.
Ensure the target element has a matching `id` attribute. For asynchronously loaded content, consider increasing the `timeout` prop on `HashLink` if content takes longer to render.
Verify that your application uses `BrowserRouter` and that the `id` attribute of your target element precisely matches the hash fragment (e.g., `<HashLink to="/#my-id">` targets `<div id="my-id">`).
Ensure both the path and the hash fragment in the `to` prop of `NavHashLink` exactly match the current URL for the active styles to apply.