Created
August 24, 2020 18:29
-
-
Save mrcoles/79659ce4406e7ce29ffa2c1402844afc to your computer and use it in GitHub Desktop.
A simple React component meant for form editing that will conditionally block page unloads and React Router navigation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { useBeforeunload } from 'react-beforeunload'; | |
import { Prompt } from 'react-router'; | |
const DEFAULT_MESSAGE = 'You will lose unsaved changes if you leave this page.'; | |
type BlockUnloadProps = { | |
when?: boolean; | |
message?: string; | |
}; | |
const BlockUnload = ({ when, message }: BlockUnloadProps) => { | |
message = message || DEFAULT_MESSAGE; | |
useBeforeunload(() => { | |
return when ? message : undefined; | |
}); | |
return <Prompt when={when} message={message} />; | |
}; | |
export default BlockUnload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment