Passed
Push — task/skillcategory-admin ( e35471 )
by
unknown
05:33
created

resources/assets/js/components/ScrollToTop.tsx   A

Complexity

Total Complexity 4
Complexity/F 0

Size

Lines of Code 45
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 33
mnd 4
bc 4
fnc 0
dl 0
loc 45
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import React, { useEffect, useState } from "react";
2
3
interface ScrollToTopProps {
4
  /** The top position of element relative to the viewport.  */
5
  offsetTop?: number;
6
  /** Set the scroll behavior to 'auto'. Default = 'smooth' */
7
  scrollBehaviorAuto?: boolean;
8
  children: React.ReactElement | null;
9
}
10
11
const ScrollToTop: React.FunctionComponent<ScrollToTopProps> = ({
12
  offsetTop,
13
  scrollBehaviorAuto,
14
  children,
15
}): React.ReactElement => {
16
  const [prevPathname, setPrevPathName] = useState(window.location.pathname);
17
18
  const setScrollBehaviour = (scrollBehavior): void => {
19
    const body: HTMLElement | null = document.querySelector("html");
20
    if (body) {
21
      body.style.scrollBehavior = scrollBehavior;
22
    }
23
  };
24
  useEffect(() => {
25
    if (prevPathname !== window.location.pathname) {
26
      // switch to auto scroll transition
27
      if (scrollBehaviorAuto) setScrollBehaviour("auto");
28
29
      if (offsetTop) {
30
        window.scrollTo(0, offsetTop);
31
      } else {
32
        window.scrollTo(0, 0);
33
      }
34
35
      // switch back to smooth scrool transition
36
      setScrollBehaviour("smooth");
37
    }
38
39
    setPrevPathName(window.location.pathname);
40
  }, [prevPathname, scrollBehaviorAuto, children, offsetTop]);
41
  return <>{children}</>;
42
};
43
44
export default ScrollToTop;
45