this.props.history.push is undefined

Viewed 3138

I am creating a form with some predefined values, and i want to route to the dashboard page once the form is submitted. I am using handleLoginSubmit func on the onsubmit of the form. For that, I have the following code:

handleLoginSubmit = (e) => {
e.preventDefault();
let hardcodedCred = {
  email: "email@email.com",
  password: "password123",
};

if (
  this.state.email == hardcodedCred.email &&
  this.state.password == hardcodedCred.password
) {
  //combination is good. Log them in.
  //this token can be anything. You can use random.org to generate a random string;
  // const token = "123456abcdef";
  // sessionStorage.setItem("auth-token", token);
  //go to www.website.com/todo
  // history.push("/dashboard");
  this.props.history.push("/dashboard");

  // console.log(this.state.route);
  console.log(this.context);
  console.log("logged in");

  // <Link to={location} />;
} else {
  //bad combination
  alert("wrong email or password combination");
}


};

But, I am receiving the error saying that history is undefined. Please help me out here

3 Answers

You need to export the component with router to access history

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

export default withRouter(ComponentName)

if your component is linked with Route then you can directly access that in this.props but if its sub-component or children of some component then you cant access it into this.props.

so there is multiple way to solve it

  1. pass history as props in your component if that component is linked with Route
<Component history={this.props.history} />
  1. use withRouter HOC, that bind all Route props in your component
import { withRouter } from 'react-router-dom';

export default withRouter(Component)
  1. use useHistory hook and save it to constant ( functional component )
import { useHistory } from 'react-router-dom';

const history = useHistory();

Update of Nisharg Shah's answers of part 3 for future reference.

If you are using react-router-dom v6, then use useNavigate instead of useHistory.

You can use:

import { useNavigate } from "react-router-dom";

let navigate = useNavigate();

OR

import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}
Related