Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigating Programmatically in React-Router v4

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?

like image 338
spik3s Avatar asked Oct 06 '16 11:10

spik3s


People also ask

How do you programmatically navigate using react router v4?

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.

How do you programmatically navigate using react router?

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.

How do you navigate on path by button click in react v6 router?

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.


1 Answers

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>     )   } } 
like image 58
Harlan T Wood Avatar answered Sep 24 '22 14:09

Harlan T Wood