Skip to content
This repository was archived by the owner on May 1, 2025. It is now read-only.

HashScroll

Yash Totale edited this page Nov 29, 2020 · 5 revisions

HashScroll

Scrolls to child element when the specified hash is present in the url

Props

hash

  • Required
  • Type: string
  • The hash that should trigger scroll to the element
  • Can include or exclude leading "#"
  • Examples:
    • "#example"
    • "example"

behavior

position

requiredPathname

scrollFunc

children

  • Required
  • Type: ReactElement
  • Must be a singular child (which CANNOT be text)
  • Custom children must forward refs to a dom element

Example

import React from "react";
import { BrowserRouter } from "react-router-dom"; //Can use HashRouter or MemoryRouter as well
import { HashScroll } from "react-hash-scroll";

const App = () => {
  return (
    <BrowserRouter>
      <HashScroll hash="#hash1" position="center">
        <HashChild>Element #1</HashChild>
      </HashScroll>
      <HashScroll hash="#hash2" requiredPathname="/docs">
        <div>Element #2</div>
      </HashScroll>
      <HashScroll hash="#example" position="end">
        Hello! (This does not work! Neither does <>Hello!</>) Children must be elements!
      </HashScroll>
    </BrowserRouter>
  );
};

const HashChild = React.forwardRef((props, ref)) => ( // Must forward refs for custom HashScroll children
  <div ref={ref}>{props.children}</div>
)
Clone this wiki locally