1import React, { useEffect, useRef } from 'react';
2import { useLocation } from 'react-router-dom';
3import { useMarkdownPage } from 'react-static-plugin-md-pages';
4
5const parsePathname = pathname => {
6 const match = pathname && pathname.match(/#[a-z|-]+/);
7 return match && match[0];
8};
9
10export const ScrollToTop = () => {
11 const inputRef = useRef(null);
12 const location = useLocation();
13 const md = useMarkdownPage();
14
15 const hash = location.hash || parsePathname(location.pathname);
16
17 useEffect(() => {
18 if (hash && md) {
19 inputRef.current.click();
20 } else {
21 window.scrollTo(0, 0);
22 }
23 }, [hash, md]);
24
25 return <a href={hash} ref={inputRef} />;
26};