Skip to content

Commit

Permalink
Add unstable_usePrompt (#9932)
Browse files Browse the repository at this point in the history
  • Loading branch information
brophdawg11 authored Jan 18, 2023
1 parent 4326424 commit 0529002
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/spicy-nails-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router-dom": patch
---

Add `unstable_usePrompt`
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit 0529002

Please sign in to comment.