DEVDEV

useBeforeUnloadAlert

作成日
2022-11-08
更新日
2022-11-08

TODO: ブラウザバックも制御したい

useWindowEvent

ts
import { DependencyList, useEffect } from 'react' export const useWindowEvent = <K extends keyof WindowEventMap>( type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, deps: DependencyList, options?: boolean | AddEventListenerOptions ) => useEffect(() => { if (window) { window.addEventListener(type, listener, options) return () => { window.removeEventListener(type, listener, options) } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [deps])

useBeforeUnloadAlert

ts
import { DependencyList, useCallback } from 'react' import { useWindowEvent } from './useWindowEvent' export const useBeforeUnloadAlert = (diff: boolean | (() => boolean), deps: DependencyList) => { const handler = useCallback( (e: BeforeUnloadEvent) => { if (typeof diff === 'boolean' ? diff : diff()) { e.preventDefault() e.returnValue = '' } }, // eslint-disable-next-line react-hooks/exhaustive-deps [deps] ) useWindowEvent('beforeunload', handler, deps) }

使い方

tsx
useBeforeUnloadAlert(dirty, [dirty])

Related

TAGS

React Hooks
ReactJS

SHARE