简体   繁体   中英

Blocking navigation in React App

I am having an issue with navigation blocking in React.

I use React + Redux with React Router. I have been using the component in order to prevent navigation from incomplete forms within React. This works fine as long as the navigation is actually within React. What it doesn't block, however, is navigation via URL entry, or clicking on an external hyperlink.

Is there an accepted method in React for handling external hyperlinks and blocking navigation outside of React?

You didn't provide any code here, so I'm trying to guess. If I understand you correctly, you are able to manage you internal redirects thought the React app via react-router without any issues.

As per your statement:

What it doesn't block, however, is navigation via URL entry, or clicking on an external hyperlink.

Let's tackle both questions. First can't prevent a user from going to the navigation bar and enter a new URL, that done by design on the browsers side, it would be bad for the user, and of course invasive!

But regarding your second question about clicking on a link that will send you outside your domain or application, you can do something about it.

You have multiple options here, I will give you three:

First: Use history.block

You can block or better said, ask the user to acknowledge the transition to another page by using history.block

As an example from the history docs:

const unblock = history.block('Are you sure you want to leave this page?')

Second: Use history.push instead of href

Just don't use anchor elements href , but rely on the history of react-router .

You can read more about it here: react-router/history

But basically you can wire your redirection using the push method from history, which will look something like:

onClick() {
    //code to control if you want to redirect or not
    history.push('http://yoururl.com');
}

Third: Use Redirect component with conditional rendering

Then you have other options like for example using conditional rendering combined with Redirect components, but the other approach would be enough to solve your problem.

I think you are looking for Blocking Transitions under the history api for React Router.

As per the example on react router history github page:

You can register a simple prompt message that will be shown to the user before they navigate away from the current page.

const unblock = history.block('Are you sure you want to leave this page?')

Detailed info at https://github.com/ReactTraining/history#properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM