Skip to content

Instantly share code, notes, and snippets.

@kaungmyatlwin
Last active August 18, 2021 16:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaungmyatlwin/115469e71b19e751592598c410245754 to your computer and use it in GitHub Desktop.
Save kaungmyatlwin/115469e71b19e751592598c410245754 to your computer and use it in GitHub Desktop.
React Navigation Blocker with React Router Prompt. Usage included.
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import NavigationBlocker from './NavigationBlocker';
export default () => {
const [hasUnsavedProgress, setHasUnsavedProgress] = useState(false);
const [inputValue, setInputValue] = useState('');
const history = useHistory();
useEffect(() => {
setHasUnsavedProgress(inputValue.length > 0);
}, [inputValue]);
function onClickCancel() {
history.push('/some-where');
}
return (
<>
<NavigationBlocker
shouldBlockNavigation={hasUnsavedProgress}
message="You have unsaved changes. Do you want to leave this page?" />
<input value={inputValue} onChange={e => setInputValue(e.target.value)} />
<button onClick={onClickCancel}>Cancel</button>
</>
);
}
import React, { useEffect } from 'react';
import { Prompt } from 'react-router-dom';
export default ({ shouldBlockNavigation = false, message = '' }) => {
useEffect(() => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true;
} else {
window.onbeforeunload = null;
}
// Proper clean up
return () => {
window.onbeforeunload = null;
};
}, [shouldBlockNavigation]);
return <Prompt when={shouldBlockNavigation} message={message} />;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment