Skip to content

Instantly share code, notes, and snippets.

@pwfisher
Created November 23, 2021 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pwfisher/d3402412ae6d0f375d780db140f8e927 to your computer and use it in GitHub Desktop.
Save pwfisher/d3402412ae6d0f375d780db140f8e927 to your computer and use it in GitHub Desktop.
ScrollToHack: scrollTo override — disable calls without "allowed" arg or property. Next.js History.scrollRestoration debug tool.
import { FC, useEffect } from 'react'
type ScrollToOptionsPlusAllowed = ScrollToOptions & { allowed: boolean }
/**
* Hack to completely disable Next.js emulation of History.scrollRestoration.
* Everywhere we want to scroll, we must add `allowed: true`.
* @see https://github.com/vercel/next.js/issues/20951#issuecomment-970710409
*/
export const ScrollToHack: FC = () => {
useEffect(() => {
const { scrollTo } = window
// @ts-ignore hackScrollTo unused
const hackScrollTo: {
(options?: ScrollToOptionsPlusAllowed | undefined): void
(x: number, y: number, allowed?: boolean): void
} = (x?: ScrollToOptionsPlusAllowed | number, y?: number, allowedArg?: boolean) => {
console.log('[hackScrollTo] start', { x, y })
if (typeof x === 'number' && typeof y === 'number') {
if (allowedArg) scrollTo(x, y)
else console.log('[hackScrollTo] not allowedArg')
return
}
if (!x) return
const { allowed, behavior, left, top } = x as ScrollToOptionsPlusAllowed
console.log(x)
if (allowed) scrollTo({ behavior, left, top })
else console.log('[hackScrollTo] not allowed')
}
// @ts-ignore hackScrollTo has extra "allowed" property
window.scrollTo = hackScrollTo
console.log('[ScrollToHack] replaced window.scrollTo')
return () => {
window.scrollTo = scrollTo
}
}, [])
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment