3

When using react-router I can use the Link element to create links that are natively handled by react router.

I see internally it calls this.context.transitionTo(...).

I want to do a navigation, but not from a link, from a dropdown selection for example. How can I do this in code? What is this.context?

I saw the Navigation mixin, but can I do this without mixin's?

Ben Johnson
  • 338
  • 1
  • 3
  • 11

2 Answers2

3

You want to install the history package npm install history and then pass an instance of it to your router:

import { Router } from "react-router";
import { createBrowserHistory } from "history";

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

Then you can programmatically navigate anywhere in your app by using withRouter to get your history instance and doing something like this history.push("/my-path").

You can also set up a file that creates/exports your history instance that you can just import.

Technically you don't need the history package as react-router will pass its own, but if you're doing this you'll prefer the flexibility that your own history instance will provide.

Chase
  • 2,206
  • 1
  • 13
  • 17
  • You can also create a history object in a separate module kinda 'history.util.js' and import it from there so as to make it accessible outside components. – Yaroslav May 19 '20 at 18:46
0

Have you tried using Redirect component from router?

This is the example:

<Redirect to="/login" exact component={Login} />
Ryukote
  • 767
  • 1
  • 10
  • 26