Prevent Navigation When SaveBar is Active

I am using the Contextual Save (SaveBar) component in Shopify. When the SaveBar is active or open, how can I prevent users from navigating to the next or previous page using the browser’s back and forward buttons?

Is there a recommended way to intercept these actions and prompt users to save their changes before leaving?


@Liam-Shopify @Benji_Yang

Hi Diwaker,

You could look into using React Routers useBlocker hook: useBlocker v6.30.0 | React Router

allows you to prevent the user from navigating away from the current location, and present them with a custom UI to allow them to confirm the navigation.

Hope this helps!

1 Like

Hello @Liam-Shopify ,

Does useBlocker work with BrowserRouter? I encountered the error: “useBlocker must be used within a data router.” when trying to use it. It seems that useBlocker is only compatible with a data router. Is there a solution for using it with BrowserRouter?

I can’t say for sure, but I do know devs have used that successfully in their app UIs in the past.

1 Like

Hello @Liam-Shopify
I tried implementing useBlocker in my app, but it gives an error of data router as my app structure doesn’t allow me to use a data router, so it will not be possible with your solution of useBlocker. To prevent this, I tried using javascript events popState & beforeUnload, but nth is working for me.

My app uses react-router-dom v6 (use navigate) to navigate around the pages. user selects products from the main page, i.e., page 1, then a user goes to a second page where they can confirm products, and then the user lands on the third page where I’ve implemented a contextual save bar. When a user clicks the browser back button, if the form is dirty, the user gets navigated to the previous page. This is not the expected behavior. We need the user to stay on the page until the user saves or clears the form data.

Please go through my code & provide us with solid fixes.The code I attached prevents 1 or 2 times; then it shows the alert box of “Leave Site?” & UI flickers.

1 Like