gitmyhub

react-router-hash-link

JavaScript ★ 0 updated 7y ago ⑂ fork

Hash link scroll functionality for React Router

React Router Hash Link Explanation

When you build a website with React Router, you might notice a frustrating problem: clicking a link that points to a specific section on a page (like #contact or #faq) doesn't automatically scroll down to that section. This library fixes that. It's a small drop-in replacement for React Router's standard Link component that actually does what users expect—it scrolls the page to match the link destination.

Here's how it works at a high level. When someone clicks one of these special links, the library finds the HTML element on the page that has a matching id (if your link says #contact, it looks for an element with id="contact"), and then scrolls that element into view. It even handles cases where content loads asynchronously, so if a section appears on the page after data finishes fetching, the scroll will still find it and work correctly.

Using it is straightforward. Instead of importing Link from React Router, you import HashLink from this library and use it exactly the same way. You can also choose how the scroll happens—you can make it smooth and gradual instead of instant, or you can write your own custom scrolling logic if you need something specific like scrolling to a spot with extra padding for a fixed header. The library also supports custom Link implementations, which is helpful if you're using a tool like Gatsby that has its own version of Link.

The main limitation is that you need to be using React Router's BrowserRouter for this to work. If you're building a standard React app with routing and navigation, this solves a real usability problem that would otherwise require you to write your own workaround.