Last active
August 18, 2021 16:38
-
-
Save kaungmyatlwin/115469e71b19e751592598c410245754 to your computer and use it in GitHub Desktop.
React Navigation Blocker with React Router Prompt. Usage included.
This file contains 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, { 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> | |
</> | |
); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment