is there a way to detect when the user is about to navigate away?
Is there a way to detect when the user is about to navigate to a different page? I am making a custom unsaved changes notifier
3 Replies
Hi @Syn. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Yes, Refine provides a way to detect when a user is about to navigate away from the current page without saving changes. This is done using the
UnsavedChangesNotifier
component and the warnWhenUnsavedChanges
feature.
The UnsavedChangesNotifier
component enables the warnWhenUnsavedChanges
feature of Refine. It shows a warning message when a user tries to navigate away from the current page without saving changes. It also checks for the beforeunload
event to warn the user when they try to close the browser tab or window.
To enable this feature, you need to place the UnsavedChangesNotifier
component inside the <Refine>
component's children and set the warnWhenUnsavedChanges
option to true
.
Here is an example of how to use it:
The UnsavedChangesNotifier
component has two optional properties:
- translationKey
: The translation key for the warning message. Default value is warnWhenUnsavedChanges
. Useful when you use an i18n provider.
- message
: The warning message. Default value is Are you sure you want to leave? You have unsaved changes.
Useful when you don't use an i18n provider.
For more information, you can check the documentation here (https://refine.dev/docs/routing/integrations/react-router#unsavedchangesnotifier), here (https://refine.dev/docs/routing/integrations/next-js#unsavedchangesnotifier), and here (https://refine.dev/docs/routing/integrations/remix#additional-components).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@183085423604662273> kapa.ai is still learning and improving, please let us know how it did by reacting below
harsh-harlequin•7mo ago
Hello @Syn,
you can check our source code https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/react-router-v6/src/unsaved-changes-notifier.tsx#L19 https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/remix/src/unsaved-changes-notifier.tsx#L32 https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/nextjs-router/src/pages/unsaved-changes-notifier.tsx#L43
you can check our source code https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/react-router-v6/src/unsaved-changes-notifier.tsx#L19 https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/remix/src/unsaved-changes-notifier.tsx#L32 https://github.com/refinedev/refine/blob/4d76a96b068bb633046c5bb3aaef0981521b1898/packages/nextjs-router/src/pages/unsaved-changes-notifier.tsx#L43