I couldn't wait and I jumped into using the latest alpha version of react-router
v4. The all-new <BrowserRouter/>
is great in keeping your UI in sync with the browser history, but how do I use it to navigate programmatically?
There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.
The react-router-dom package makes it simple to create new routes. To begin, you wrap the entire application with the <BrowserRouter> tag. We do this to gain access to the browser's history object. Then you define your router links, as well as the components that will be used for each route.
To redirect page on click of a button with React Router v6, we use the useNavigate hook. to call the useNavigate hook to return the navigate function. Then we call navigate with path to navigate to the path in the routeChange function.
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> ) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With