Skip to content

Commit

Permalink
feat: update scroll to top with better logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Marvin Heilemann committed Mar 4, 2020
1 parent 24b333b commit a2d506b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 54 deletions.
8 changes: 4 additions & 4 deletions src/components/ScrollToTop.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import React, { useState } from 'react'
import { animateScroll } from 'react-scroll'

import Icon from './Icon'
import { useScrollPosition } from '../hooks/use-scroll-position'
import { useScroll } from '../hooks/use-window'

const ScrollToTop = () => {
const [visible, setVisibility] = useState(false)

useScrollPosition(({ currPos }) => {
if (currPos.y < -600) {
useScroll(({ top }) => {
if (top > 600) {
setVisibility(true)
} else {
setVisibility(false)
Expand All @@ -31,7 +31,7 @@ const ScrollToTop = () => {
tabIndex="0"
role="button"
>
<Icon name="arrow-top" />
<Icon name="arrow-up" />
</div>
)
}
Expand Down
50 changes: 0 additions & 50 deletions src/hooks/use-scroll-position.js

This file was deleted.

35 changes: 35 additions & 0 deletions src/hooks/use-window.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useLayoutEffect } from 'react'
import debounce from 'lodash/debounce'

const isBrowser = typeof window !== `undefined`

function getBoundingRect() {
if (!isBrowser) return { left: 0, top: 0, width: 0, height: 0 }

return {
left: window.scrollX,
top: window.scrollY,
width: window.innerWidth,
height: window.innerHeight,
}
}

function handler(event, effect, wait) {
const handleScroll = debounce(() => {
effect(getBoundingRect())
}, wait)

window.addEventListener(event, handleScroll)

return () => window.removeEventListener(event, handleScroll)
}

function useScroll(effect, wait = 250) {
useLayoutEffect(() => handler('scroll', effect, wait))
}

function useResize(effect, wait = 100) {
useLayoutEffect(() => handler('resize', effect, wait))
}

export { getBoundingRect, useScroll, useResize }

0 comments on commit a2d506b

Please sign in to comment.