-
Notifications
You must be signed in to change notification settings - Fork 372
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a scroll to top button, haven't styled it because I don't know how to add it to the main file, typically named App.jsx in react projects. This is my first time working in TypeScript and Next.js
- Loading branch information
1 parent
fd91540
commit d214e95
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { useEffect, useState } from 'react'; | ||
import { IconButton } from '@chakra-ui/react'; | ||
import { ArrowUpIcon } from '@chakra-ui/icons'; | ||
|
||
const ScrollToTopButton = () => { | ||
const [isVisible, setIsVisible] = useState(false); | ||
|
||
const toggleVisibility = () => { | ||
if (window.scrollY > 200) { | ||
setIsVisible(true); | ||
} else { | ||
setIsVisible(false); | ||
} | ||
}; | ||
const scrollToTop = () => { | ||
window.scrollTo({ | ||
top: 0, | ||
behavior: 'smooth', | ||
}); | ||
}; | ||
|
||
useEffect(() => { | ||
window.addEventListener('scroll', toggleVisibility); | ||
return () => window.removeEventListener('scroll', toggleVisibility); | ||
}, []); | ||
|
||
return ( | ||
isVisible && ( | ||
<IconButton | ||
position="fixed" | ||
bottom="20px" | ||
right="20px" | ||
colorScheme="teal" | ||
icon={<ArrowUpIcon />} | ||
onClick={scrollToTop} | ||
aria-label="Scroll to top" | ||
size="lg" | ||
boxShadow="lg" | ||
zIndex="1000" | ||
/> | ||
) | ||
); | ||
}; | ||
|
||
export default ScrollToTopButton; |