Sometimes, we might want to ask the user to confirm that they want to navigate away from a page. This is useful if the user is in the middle of data entry on a page and presses a navigation link to go to a different page before they have saved the data. The Prompt component in React Router allows us to do this, as set out in the following steps:
- In our app, we are going to prompt users to confirm that they want to navigate away from the Product page if they haven't added the product to their basket. First, in ProductPage.tsx, let's import the Prompt component from React Router:
import { Prompt, RouteComponentProps } from "react-router-dom";
- The Prompt component invokes a confirmation dialog during navigation when a certain condition is met. We can use the Prompt component in our JSX as follows:
<div className="page-container"...