UPDATE: 2022: React Router v6.6.1 with useNavigate
The useHistory()
hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows:
import { useNavigate } from "react-router-dom";
function HomeButton() {
const navigate = useNavigate();
function handleClick() {
navigate("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
React Router v5.1.0 with hooks
There is a new useHistory
hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
React Router v4
With v4 of React Router, there are three approaches that you can take to programmatic routing within components.
- Use the
withRouter
higher-order component.
- Use composition and render a
<Route>
- Use the
context
.
React Router is mostly a wrapper around the history
library. history
handles interaction with the browser's window.history
for you with its browser and hash histories. It also provides a memory history which is useful for environments that don't have a global history. This is particularly useful in mobile app development (react-native
) and unit testing with Node.
A history
instance has two methods for navigating: push
and replace
. If you think of the history
as an array of visited locations, push
will add a new location to the array and replace
will replace the current location in the array with the new one. Typically you will want to use the push
method when you are navigating.
In earlier versions of React Router, you had to create your own history
instance, but in v4 the <BrowserRouter>
, <HashRouter>
, and <MemoryRouter>
components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the history
instance associated with your router available through the context, under the router
object.
1. Use the withRouter
higher-order component
The withRouter
higher-order component will inject the history
object as a prop of the component. This allows you to access the push
and replace
methods without having to deal with the context
.
import { withRouter } from 'react-router-dom'
// this also works with react-router-native
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
2. Use composition and render a <Route>
The <Route>
component isn't just for matching locations. You can render a pathless route and it will always match the current location. The <Route>
component passes the same props as withRouter
, so you will be able to access the history
methods through the history
prop.
import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
3. Use the context*
But you probably should not
The last option is one that you should only use if you feel comfortable working with React's context model (React's Context API is stable as of v16).
const Button = (props, context) => (
<button
type='button'
onClick={() => {
// context.history.push === history.push
context.history.push('/new-location')
}}
>
Click Me!
</button>
)
// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.
The router will add a history
object to your component in the props
hash. So in your component, simply do:
this.props.history.push('/mypath')
Here is a full example:
In App.js
:
import React from 'react'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import Login from './Login'
export default class App extends React.Component {
render() {
return (
<Router>
<div>
<Route exact path='/login' component={Login} />
</div>
</Router>
)
}
}
In Login.js
:
import React, {PropTypes} from 'react'
export default class Login extends React.Component {
constructor(props) {
super(props)
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin(event) {
event.preventDefault()
// do some login logic here, and if successful:
this.props.history.push(`/mypath`)
}
render() {
return (
<div>
<form onSubmit={this.handleLogin}>
<input type='submit' value='Login' />
</form>
</div>
)
}
}
Best Answer
If you are targeting browser environments, you need to use
react-router-dom
package, instead ofreact-router
. They are following the same approach as React did, in order to separate the core, (react
) and the platform specific code, (react-dom
,react-native
) with the subtle difference that you don't need to install two separate packages, so the environment packages contain everything you need. You can add it to your project as:yarn add react-router-dom
or
npm i react-router-dom
The first thing you need to do is to provide a
<BrowserRouter>
as the top most parent component in your application.<BrowserRouter>
uses the HTML5history
API and manages it for you, so you don't have to worry about instantiating it yourself and passing it down to the<BrowserRouter>
component as a prop (as you needed to do in previous versions).In V4, for navigating programatically you need to access the
history
object, which is available through Reactcontext
, as long as you have a<BrowserRouter>
provider component as the top most parent in your application. The library exposes through context therouter
object, that itself containshistory
as a property. Thehistory
interface offers several navigation methods, such aspush
,replace
andgoBack
, among others. You can check the whole list of properties and methods here.Important Note to Redux/Mobx users
If you are using redux or mobx as your state management library in your application, you may have come across issues with components that should be location-aware but are not re-rendered after triggering an URL updateThat's happening because
react-router
passeslocation
to components using the context model.The 2 approaches for solving this are:
<Route />
. The currentlocation
object is one of the props that a<Route>
passes to the component it renderswithRouter
higher-order component, that in fact has the same effect and injectslocation
as a propSetting that aside, there are four ways to navigate programatically, ordered by recommendation:
1.- Using a
It promotes a declarative style. Prior to v4,<Route>
Component<Route />
components were placed at the top of your component hierarchy, having to think of your routes structure beforehand. However, now you can have<Route>
components anywhere in your tree, allowing you to have a finer control for conditionally rendering depending on the URL.Route
injectsmatch
,location
andhistory
as props into your component. The navigation methods (such aspush
,replace
,goBack
...) are available as properties of thehistory
object.There are 3 ways to render something with a
Route
, by using eithercomponent
,render
orchildren
props, but don't use more than one in the sameRoute
. The choice depends on the use case, but basically the first two options will only render your component if thepath
matches the url location, whereas withchildren
the component will be rendered whether the path matches the location or not (useful for adjusting the UI based on URL matching).If you want to customise your component rendering output, you need to wrap your component in a function and use the
render
option, in order to pass to your component any other props you desire, apart frommatch
,location
andhistory
. An example to illustrate:2.- Using
withRouter
HoCThis higher order component will inject the same props as
Route
. However, it carries along the limitation that you can have only 1 HoC per file.3.- Using a
Rendering aRedirect
component<Redirect>
will navigate to a new location. But keep in mind that, by default, the current location is replaced by the new one, like server-side redirects (HTTP 3xx). The new location is provided byto
prop, that can be a string (URL to redirect to) or alocation
object. If you want to push a new entry onto the history instead, pass apush
prop as well and set it totrue
4.- Accessing
A bit discouraged because context is still an experimental API and it is likely to break/change in future releases of Reactrouter
manually through contextNeedless to say there are also other Router components that are meant to be for non browser ecosystems, such as
<NativeRouter>
that replicates a navigation stack in memory and targets React Native platform, available throughreact-router-native
package.For any further reference, don't hesitate to take a look at the official docs. There is also a video made by one of the co-authors of the library that provides a pretty cool introduction to react-router v4, highlighting some of the major changes.