-
-
Notifications
You must be signed in to change notification settings - Fork 167
/
ScrollToTop.tsx
65 lines (56 loc) · 1.27 KB
/
ScrollToTop.tsx
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
54
55
56
57
58
59
60
61
62
63
64
65
import { ActionIcon, Portal, Transition } from '@mantine/core';
import { useEffect, useState } from 'react';
import { IconUp } from '../icons/Up';
import classes from './ScrollToTop.module.css';
interface ScrollToTopProps {
containerId: string;
targetRef: React.RefObject<HTMLElement>;
}
const scrollUp = () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
};
const ScrollToTop = ({ containerId, targetRef }: ScrollToTopProps) => {
const [showButton, setShowButton] = useState(false);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setShowButton(!entry.isIntersecting);
},
{ threshold: 0.5 },
);
const targetNode = targetRef.current;
if (targetNode) {
observer.observe(targetNode);
}
return () => {
if (targetNode) {
observer.unobserve(targetNode);
}
};
}, [targetRef]);
return (
<Transition
mounted={showButton}
transition="fade-up"
duration={300}
timingFunction="ease"
>
{(styles) => (
<Portal target={containerId}>
<ActionIcon
style={styles}
className={classes.button}
onClick={scrollUp}
aria-label="Scroll to top"
>
<IconUp height={24} width={24} />
</ActionIcon>
</Portal>
)}
</Transition>
);
};
export { ScrollToTop };