Skip to content
Advertisement

Why history.push does not work in route “/” in react?

In a React project I used react-router-dom. my question is why in route “/” history.push not worked ?

  this.props.history.push({
                    pathname:"/searchpost",
                    data:data,
                    backg: c,
                    texts:  " tags"+t,
                });

Advertisement

Answer

Let’s refer to this article: https://codesource.io/how-to-use-this-props-history-push-on-your-react-project/

It claims that the method has two parameters:

  • path
  • [state]

The state parameter is optional, but it needs to be an object. Example:

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

export default withRouter(MyComponent);

Your error therefore is that you include the path into the state, so the function does not know where to go. Maybe this would work better:

this.props.history.push("/searchpost", {
  data: data,
  backg: c,
  texts: " tags" + t,
});

I’m not very experienced with React, so if I’m totally wrong, please let me know.

Advertisement