Skip to content

Instantly share code, notes, and snippets.

@anhtran
Created December 8, 2020 05:32
Show Gist options
  • Save anhtran/8f31bd207faa8d3ab297e286c102a275 to your computer and use it in GitHub Desktop.
Save anhtran/8f31bd207faa8d3ab297e286c102a275 to your computer and use it in GitHub Desktop.
Simple scroll to top button for react
// <ScrollButton scrollStepInPx='50' delayInMs='16.66' />
import styled from '@emotion/styled'
import tw from 'twin.macro'
import ArrowUpIcon from 'bootstrap-icons/icons/arrow-up.svg'
import React, { useEffect, useState } from 'react'
import { useWindowScroll } from 'react-use'
function ScrollButton ({ scrollStepInPx, delayInMs }) {
const [intervalId, setIntervalId] = useState(0)
const { y } = useWindowScroll()
useEffect(() => {
if (window.pageYOffset === 0) {
clearInterval(intervalId)
}
}, [y])
const scrollStep = () => {
window.scroll(0, window.pageYOffset - scrollStepInPx)
clearInterval(intervalId)
}
const scrollToTop = () => {
const intervalId = setInterval(scrollStep, delayInMs)
setIntervalId(intervalId)
}
return (
<BackTopButton onClick={() => scrollToTop()}>
<ArrowUpIcon />
</BackTopButton>
)
}
// language=SCSS prefix=*{ suffix=}
const BackTopButton = styled.button`
display: flex;
align-items: center;
justify-content: center;
position: fixed;
right: 20px;
bottom: 70px;
width: 48px;
height: 48px;
border-radius: 50%;
border: none;
${tw`bg-gray-900 bg-opacity-80`}
&:active {
${tw`bg-gray-900 bg-opacity-90`}
}
&:focus {
outline: none;
}
svg {
width: 24px;
height: 24px;
${tw`fill-current text-white`}
}
`
export default ScrollButton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment