In React applications, to prevent route changes when users navigate away from the current page, you can use the Prompt component from react-router-dom to display a confirmation prompt. The Prompt component registers a prompt message that triggers when users attempt to navigate away from the current page.
Steps to Use Prompt:
-
Import the Prompt Component: First, ensure that
react-router-domis installed and imported.javascriptimport { Prompt } from 'react-router-dom'; -
Use Prompt in Your Component: In your React component, add the
Promptcomponent and set thewhenandmessageprops. Thewhenprop specifies the condition under which route changes are blocked, and themessageprop defines the prompt message displayed when leaving the page.javascriptclass MyComponent extends React.Component { state = { isDataChanged: false }; handleDataChange = () => { this.setState({ isDataChanged: true }); }; render() { return ( <div> <Prompt when={this.state.isDataChanged} message="Data has been modified. Are you sure you want to leave? Unsaved changes will be lost." /> {/* Form or other components that can modify state */} </div> ); } }In the above example, the
Promptcomponent displays a warning message only whenisDataChangedistrue(i.e., data has been modified). This message can be a static string or a function returning a string, depending on the complexity of passing additional context information. -
Customize Leave Confirmation Logic: For more complex leave confirmation logic, pass a function to the
messageprop. This function receives the new location and a callback function as parameters, allowing you to dynamically decide whether navigation is allowed based on this information.javascript<Prompt message={(location) => `Are you sure you want to go to ${location.pathname}?`} />
Important Notes:
- The
Promptcomponent depends on theRoutercontext, so it must be used inside the<Router>component. - Using the
Promptcomponent effectively prevents users from accidentally leaving the page without saving changes, which is particularly important for protecting form data. - After users confirm leaving the page, if you need to perform cleanup or save operations, you may need to combine it with React lifecycle methods or React Hooks for implementation.
This approach is highly effective for managing user navigation within the application, preventing users from losing important data due to accidental actions.