generated from mateusfg7/nextjs-setup
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(ui): add "go to top" button on post pages
resolve #29
- Loading branch information
Showing
2 changed files
with
53 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
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,51 @@ | ||
'use client' | ||
|
||
import { CaretUp } from "@phosphor-icons/react" | ||
import { useEffect, useState } from "react" | ||
|
||
export function TopButton() { | ||
const [percentScrollPosition, setPercentScrollPosition] = useState(0) | ||
const [scrollPosition, setScrollPosition] = useState(0) | ||
const [maxScrollValue, setMaxScrollValue] = useState(0) | ||
|
||
function handleScroll() { | ||
if (window) { | ||
setScrollPosition(window.scrollY) | ||
} | ||
if (document) { | ||
setMaxScrollValue( | ||
document.documentElement.scrollHeight - | ||
document.documentElement.clientHeight | ||
) | ||
} | ||
} | ||
|
||
useEffect(() => { | ||
handleScroll() | ||
|
||
if (window) { | ||
window.addEventListener('scroll', handleScroll, { passive: true }) | ||
} | ||
}, []) | ||
|
||
useEffect(() => { | ||
setPercentScrollPosition( | ||
Math.round((scrollPosition / maxScrollValue) * 100) | ||
) | ||
}, [scrollPosition, maxScrollValue]) | ||
|
||
const isNotOnTop = percentScrollPosition > 0 | ||
|
||
const scrollToTop = () => { | ||
window.scrollTo({ | ||
top: 0, | ||
behavior: 'smooth', | ||
}); | ||
}; | ||
|
||
return ( | ||
<button onClick={scrollToTop} title="Go to top" className={`fixed right-7 bottom-7 rounded-full hidden md:flex items-center justify-center p-2 hover:bg-neutral-200 hover:dark:bg-neutral-900 ${isNotOnTop ? 'opacity-100' : 'opacity-0'}`}> | ||
<CaretUp className="text-2xl" /> | ||
</button> | ||
) | ||
} |