3

I'm learning React Route to help me build an app that could redirect from login page to home page after successfully sign in.

I read the official tutorial here: https://github.com/reactjs/react-router-tutorial/tree/master/lessons/12-navigating

In this lesson, they introduced two ways to navigate Programmatically, which are, browserHistory and context.route. And they said there is a potential problem with browserHistory that:

If you pass a different history to Router than you use here, it won't work. It's not very common to use anything other than browserHistory, so this is acceptable practice.

Can you give me an example about what is If you pass a different history to Router than you use here?

I tried this two ways in my application and cant find any difference. THX!

1 Answer 1

1

That's a pretty old tutorial. I would recommend looking at the official react router documentation instead.

The example you provided uses the browserHistory instance directly to call the history api methods. This will work if you configure react router to use browser history, but there are different history types (hash history, memory history, etc), and it's even possible to have multiple instances of browserHistory. While all the different history types support the push method, if you originally configure react router to use hash history, but within your component, you import browser history, the push call will simply not work because your router is not configured to listen to that browser history instance.

While you can use context to get the router instance, a cleaner approach is to use withRouter HOC to inject the router instance into your component as a prop. You can then call router.push and not have to worry about what kind of history you're using.

You can read more about history here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.