by Sai gowtham

How to redirect from one page to another page in React Router

How to redirect from one page to another page in React Router

In this tutorial, we are going to learn about how to redirect a user from one page to another page in react-router using Redirect component.

Suppose we have a path /blog in our app and we updated it to /tutorials so that now if any user tries to navigate to /blog we need to redirect them to /tutorials, we can do it by using a Redirect component provided by the react-router-dom library.

In the below code, we first imported the Redirect component from the react-router-dom library.

Redirect component accepts two props from and to.

from : we need to type old path here (/blog).

to: we need to type a new path here (/tutorials).

index.js
import React from 'react';
import {BrowserRouter as Router,Route,
 Redirect,Switch} from 'react-router-dom';import Home from './App.js';
import Tutorials from './tutorials.js';

function Routes(){
    return (
    <Router>
      <div>
        <Switch>
           <Route path="/" component = {Home}>
           <Redriect from='/blog/' to="/tutorials/" />           <Route path="/tutorials/" component={About} />
        </Switch>
      </div>
    </Router>
    )
}

Now, if any user visits /blog he or she will be redirected to /tutorials.

Programmatic navigation

Programmatic navigation means redirection occurs on that route when a particular event happens, for example when a user clicks on a login button, if login is successful we need to redirect them to private route.

There are two possible ways we can do Programmatic navigation.

First way using the Redirect component.

Login.js
import React from 'react';
import {Redirect} from 'react-router-dom';
class Login extends React.Component {

  onSubmit = () => {
     if(userFound){
         return  <Redirect  to="/posts/" />     }
  }

  render() {
    return (
      <form>
        <input placeholder="email" type="email" />
        <input placeholder="password" type="password" />
        <button onClick={this.onSubmit}>Login</button>      </form>
    )
  }
}

export default Login;

Second way using history object which is available inside props, passed by the react-router library.

Login.js
import React from 'react';
class Login extends React.Component {

  onSubmit = () => {
     if(userFound){
         this.props.history.push('/posts/');     }
  }

  render() {
    return (
      <form>
        <input placeholder="email" type="email" />
        <input placeholder="password" type="password" />
        <button onClick={this.onSubmit}>Login</button>      </form>
    )
  }
}

export default Login;