-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathScrollTop.js
66 lines (56 loc) · 1.41 KB
/
ScrollTop.js
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
66
import React from 'react';
import ArrowUp from '../Icon/ArrowUp';
import Button from './index';
const styles = {
hide: {
bottom: 90,
right: -65,
},
show: {
right: 15,
},
};
export default class ScrollTop extends React.Component {
state = {
scrollTopClass: '',
};
componentDidMount() {
this.scrollHandler();
window.addEventListener('scroll', this.scrollHandler);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.scrollHandler);
}
scrollHandler = () => {
const scrollToTopClass = window.pageYOffset > window.innerHeight / 4 ? 'opacity-100' : '';
if (scrollToTopClass !== this.state.scrollToTopClass) {
this.setState({
scrollToTopClass,
});
}
};
scrollToTop = () => {
window.scrollTo({
behavior: 'smooth',
top: 0,
});
};
render() {
const { scrollToTopClass } = this.state;
return (
<div
aria-label="Scroll to the top of the page"
tabIndex={scrollToTopClass ? 0 : -1}
className={`transition-slow fixed cursor-pointer opacity-0 z-10 ${scrollToTopClass}`}
style={{
...styles.hide,
...(scrollToTopClass && styles.show),
}}
>
<Button onClick={this.scrollToTop} onKeyPress={this.scrollToTop} className="px-3">
<ArrowUp width={27} height={28} color="currentColor" />
</Button>
</div>
);
}
}