react

How To Use this.props.history.push On Your React Project


In this article, you will learn how to use this.props.history.push in your react project.

The history.push() function belongs to react-router-dom and used to move from the current page to another one. It takes the first argument as a destination path and a second argument as the state.

history.push(path, [state])

Let’s say we want to move to the dashboard page, all we need to do is:

class MyComponent extends React.Component { 
  ... 
  myFunction() { 
    this.props.history.push("/dashboard"); 
  } 
  ... 
} 

export default withRouter(MyComponent);

We can also bring the data from the current page to our destination page using the second argument of this function:

class MyComponent extends React.Component { 
  ... 
  myFunction() { 
    this.props.history.push("/dashboard", { state: 'sample data'}); 
  } 
  ... 
} 

export default withRouter(MyComponent);

Note: You can only use this.props.history.push() function inside the component page that already listed on your project route, or simply use the withRouter() HOC if the component is not available in the route list.


Share on social media

//