Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created August 24, 2020 18:29
Show Gist options
  • Save mrcoles/79659ce4406e7ce29ffa2c1402844afc to your computer and use it in GitHub Desktop.
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
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