React Router V4 Navigate and Redirect Programmatically

Best way to navigate to a page using react router v4 Programmatically is by using a new Higher Order Component ( HOC ) provided by React Router V4.

withRouter provides with with a history object that we can use to navigate in our properly. Here is how we can use it.

import React from 'react';
import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
 onButtonClick(){
  let { history } = this.props;
  history.push({
   pathname: '/somepage',
   search: 'name=jhon&age=24'
  });
 }
 render(){
  return (
   <button onClick={this.onButtonClick.bind(this)} >
    Click Me
   </button>
  );
 }
}

export default withRouter(MyComponent);

To append GET parameters to the URL all you have to do is set the search key of the object that is being passed to push.

React Router V4 has introduced and new Redirect component which can be used if you want to redirect the user to a different URL.

Redirect is different from the above explained method of pushing a new URL on to the current stack. When you redirect a user the current page is replaced with the new page in the history stack and pressing the back button will no longer take you back to the previous page.

Here is how you use the Redirect component.

import React from 'react';
import { Redirect } from 'react-router-dom';

class MyComponent extends React.Component {
 constructor(props){
  super(props);
  this.state = {
   redirectMe: true
  }
 }
 render(){
  let { redirectMe } = this.state;
  if(redirectMe){
   return (
    <Redirect to="/somepage" />
   );
  }
  ...
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *