Skip to content

Instantly share code, notes, and snippets.

@khuezy
Last active October 15, 2023 13:42
Show Gist options
  • Save khuezy/34fd7fe245018887f86691463262dcba to your computer and use it in GitHub Desktop.
Save khuezy/34fd7fe245018887f86691463262dcba to your computer and use it in GitHub Desktop.
next/link patch
import { RefObject, useEffect, useState } from 'react'
export function useOnScreen(ref?: RefObject<HTMLElement>, rootMargin = '0px') {
const [isIntersecting, setIntersecting] = useState(false)
const r = ref?.current
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIntersecting(entry.isIntersecting)
}, { rootMargin }
)
r && observer.observe(r)
return () => {
r && observer.unobserve(r)
}
}, [r, rootMargin])
return isIntersecting
}
export function hasTouch() {
if ( typeof window === 'undefined' || typeof navigator === 'undefined') return false
return ( 'ontouchstart' in window ) ||
( navigator.maxTouchPoints > 0 ) ||
// @ts-ignore for MS
( navigator.msMaxTouchPoints > 0 )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment