Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unstable_usePrompt #9932

Merged
merged 4 commits into from Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/spicy-nails-compete.md
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Add `unstable_usePrompt`
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -118,10 +118,10 @@
"none": "15 kB"
},
"packages/react-router-dom/dist/react-router-dom.production.min.js": {
"none": "11 kB"
"none": "11.5 kB"
},
"packages/react-router-dom/dist/umd/react-router-dom.production.min.js": {
"none": "16.5 kB"
"none": "17 kB"
}
}
}
33 changes: 33 additions & 0 deletions packages/react-router-dom/index.tsx
Expand Up @@ -18,6 +18,7 @@ import {
useNavigate,
useNavigation,
useResolvedPath,
unstable_useBlocker as useBlocker,
UNSAFE_DataRouterContext as DataRouterContext,
UNSAFE_DataRouterStateContext as DataRouterStateContext,
UNSAFE_NavigationContext as NavigationContext,
Expand Down Expand Up @@ -1210,6 +1211,38 @@ export function useBeforeUnload(
};
}, [callback, capture]);
}

/**
* Wrapper around useBlocker to show a window.confirm prompt to users instead
* of building a custom UI with useBlocker.
*
* Warning: This has *a lot of rough edges* and behaves very differently (and
* very incorrectly in some cases) across browsers if user click addition
* back/forward navigations while the confirm is open. Use at your own risk.
*/
function usePrompt({ when, message }: { when: boolean; message: string }) {
let blocker = useBlocker(when);

React.useEffect(() => {
if (blocker.state === "blocked" && !when) {
blocker.reset();
}
}, [blocker, when]);

React.useEffect(() => {
if (blocker.state === "blocked") {
let proceed = window.confirm(message);
if (proceed) {
setTimeout(blocker.proceed, 0);
} else {
blocker.reset();
}
}
}, [blocker, message]);
}

export { usePrompt as unstable_usePrompt };

//#endregion

////////////////////////////////////////////////////////////////////////////////
Expand Down