forked from realstoman/react-tailwindcss-portfolio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseScrollToTop.jsx
53 lines (45 loc) · 1.21 KB
/
useScrollToTop.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// NOTE: This scroll to top is the actual working scroll to to when user clicks on the circle arrow that appears when use scrolls down.
// The other `ScrollToTop` component in components folder is for the default react scroll to top behavior on route visit.
import { useState, useEffect } from 'react';
import { FiChevronUp } from 'react-icons/fi';
const useScrollToTop = () => {
const [showScroll, setShowScroll] = useState(false);
useEffect(() => {
window.addEventListener('scroll', scrollToTop);
return function cleanup() {
window.removeEventListener('scroll', scrollToTop);
};
});
const scrollToTop = () => {
if (!showScroll && window.pageYOffset > 400) {
setShowScroll(true);
} else if (showScroll && window.pageYOffset <= 400) {
setShowScroll(false);
}
};
const backToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};
window.addEventListener('scroll', scrollToTop);
return (
<>
<FiChevronUp
className="scrollToTop"
onClick={backToTop}
style={{
height: 45,
width: 45,
borderRadius: 50,
right: 50,
bottom: 50,
display: showScroll ? 'flex' : 'none',
padding: 5,
}}
/>
</>
);
};
export default useScrollToTop;