Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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