Total Complexity | 4 |
Complexity/F | 0 |
Lines of Code | 45 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 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 |