-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathScrollButton.js
More file actions
50 lines (44 loc) · 1.14 KB
/
Copy pathScrollButton.js
File metadata and controls
50 lines (44 loc) · 1.14 KB
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
import React, { useEffect, useState } from 'react';
const ScrollButton = () => {
const [isVisible, setIsVisible] = useState(false);
const toggleVisibility = () => {
if (window.scrollY > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth', // Smooth scrolling
});
};
useEffect(() => {
window.addEventListener('scroll', toggleVisibility);
return () => {
window.removeEventListener('scroll', toggleVisibility);
};
}, []);
return (
<div
className={`scroll-button ${isVisible ? 'visible' : ''}`}
onClick={scrollToTop}
style={{
position: 'fixed',
right: '20px',
top: '50%',
transform: 'translateY(-50%)',
backgroundColor: 'blue',
color: 'white',
borderRadius: '50%',
padding: '10px',
cursor: 'pointer',
display: isVisible ? 'block' : 'none', // Show/hide based on scroll position
}}
>
↑
</div>
);
};
export default ScrollButton;