Detects location.hash changes and scrolls to the element with the corresponding id. Customizable scroll behavior.
npm install @cascadia-code/scroll-to-hash-element!npm !GitHub License !GitHub package.json dev/peer/optional dependency version
No longer requires react-router as dependency!
This component enables hash/anchor links to function within a React application.
It works by listening to the hash property of window.location and scrolling to the matching element if it exists.
This was originally written to solve the issue of hash links no longer working with React Router v6+, and required react-router as a dependency. However, it has been refactored to work with any router (or lack thereof).
Scrolling itself is provided by the native browser method Element.scrollIntoView()
Install the package with npm or yarn
``bash`
npm install @cascadia-code/scroll-to-hash-element
Just place this component anywhere in the top level of the application and it will work passively in the background.
`js title=App.jsx
import React from "react";
import ScrollToHashElement from "@cascadia-code/scroll-to-hash-element";
import Header from "./Header";
import Content from "./Content";
const App = () => {
return (
export default App;
`
#### With React-Router
You can create React-Router links as you normally would. For example a link to a hash element on the homepage would look like this
`js`
Link Text
or this
`js`
Link Text
a sub page like this
`js`
Our Story
#### Without React-Router
You can create standard anchor tags. For example a link to a hash element on the homepage would look like this
`js`
Link Text
or this
`js`
Link Text
a sub page like this
`js`
Our Story
You can customize the scroll behavior by passing props to the ScrollToHashElement component.
`js`
| prop | default | options |
|----------|----------|----------|
| behavior | "auto" | "auto", "instant", "smooth" |inline
| | "nearest" | "center", "end", "nearest", "start" |block
| | "start" | "center", "end", "nearest", "start"` |
You can read more about these properties here: Element.scrollIntoView()