React router prompts when routing is switched

React router version ^ 5.1.2

When the content being edited is not saved, there is a routing switch. At this time, you need to give some prompts, and the user controls whether to jump.

During the route management of react router, the Prompt component can be used to realize this function. The message attribute can accept a function and Prompt when returning string. By default, it is window.confirm to Prompt. The user can choose whether to jump or not. When returning true, the route can be switched directly without Prompt.

The Prompt can be simply encapsulated as follows:

import { Prompt} from "react-router-dom";

export default function RouterPrompt ({message,promptBoolean}) {
    // Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
    return  <Prompt message={
                        location =>
                            ? true
                            : message || 'There is unsaved content on the current page. Do you want to leave?'

When using, which component needs to be prompted at the time of leaving? Just introduce it. It can be placed anywhere in the component. Whether prompt is needed is controlled by the user.

            <div className="hardware">
                {/* This is to set whether prompt is needed according to the editing status of the input box */}
                <RouterPrompt promptBoolean={EDIT_STATUS}></RouterPrompt>
                {/* Other contents */}

The default prompt is window.confirm, but it can also be customized through getUserConfirmation.

import { HashRouter as Router} from "react-router-dom";
import { Modal} from 'antd';

// Message is the message of window.confirm, which is controlled by callback
// The Modal component of antd is directly used here
customConfirm = (message,callback) => {
        onCancel: () => {
            onOk: () => {
<Router getUserConfirmation={customConfirm}></Router>

The effect is as follows:

Tags: Javascript React Attribute

Posted on Wed, 25 Mar 2020 07:07:50 -0700 by sevenfive