본문으로 건너뛰기

BackTop

Prerequisite

npm install classnames @heroicons/react

Code

components/BackTop/index.tsx
import { useEffect } from 'react'
import type { FC } from 'react'
import { ChevronUpIcon } from '@heroicons/react/outline'
import { throttle, useObjectState } from 'services'
import classnames from 'classnames'

export interface Props {}
interface State {
isVisible: boolean
}

const BackTop: FC<Props> = () => {
const [{ isVisible }, setState] = useObjectState<State>({
isVisible: false
})

const onScroll = throttle(
(e: Event) => setState({ isVisible: window.scrollY > 400 }),
10
)

useEffect(() => {
window.addEventListener('scroll', onScroll)
return () => {
window.removeEventListener('scroll', onScroll)
}
}, [])
return (
<button
className={classnames(
'fixed bottom-5 right-5 w-12 h-12 flex items-center justify-center bg-gray-900 hover:bg-black rounded-full duration-150',
isVisible ? 'scale-100' : 'scale-0'
)}
onClick={() => window.scrollTo(0, 0)}
tabIndex={0}
>
<ChevronUpIcon className="h-7 w-7 text-white" />
</button>
)
}

export default BackTop

Example