Skip to content

HashScroll

YashTotale edited this page Dec 19, 2020 · 5 revisions

HashScroll

Summary

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

Demo

View Hash Scroll Demo

Props

hash

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

children

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

behavior

position

requiredPathname

scrollFunc

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>
)