4
votes

I'm trying to use the hook useHistory from documentation of react-router-dom.

I keep getting this error: TypeError: Cannot read property 'history' of undefined

Here an example: https://codesandbox.io/s/twilight-meadow-bwnt8?fontsize=14&hidenavigation=1&theme=dark

import React from 'react';
import { useHistory } from "react-router-dom";


function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

function App() {
  return (
     <HomeButton />
  );
}

export default App;
1
post your route configuration fileakhtarvahid
Was able to solve whith this: stackoverflow.com/questions/43822589/…Samuel Cazelli

1 Answers

4
votes

The useHistory hook only works inside of a Route.

It is the route that passes the history object to the useHistory hook. Which is why in this case it is undefined - there is no route to pass the history object to it.