React router v5 - TypeError history is undefined

Recently I was adding react router (version 5.1.7) to my side project. I wanted to add a redirect after a certain button is pressed. Unfortunately, I was receiving TypeError: history is undefined every button was pressed. It took me a while, but the fix was trivial

Before we go to the fix itself let me show the code that was causing problems

export default function App() {
  const history = useHistory()

  let redirectBackHome = () => history.push("/")

  return (
    <Router>
      <div>
        <Switch>
          <Route path="/other-component">
            <OtherComponent onClick={redirectBackHome}/>
          </Route>
          <Route path="/">
            <h2>Home</h2>
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

Code is simple, we pass a function to OtherComponent so it can redirect us back, once something is pressed there. Unfortunately, when you try to click the button inside of OtherComponent you will encounter TypeError: history is undefined with the stack trace pointing to the line which looks innocent.

Screenshot of the error. The error line is let redirectBackHome = () => history.push("/")

The problem is that you cannot use useHistory hook if your component was not rendered between Router tag and its closing.

In our case, if you want to use history in OtherComponent you need to use this hook there.

const OtherComponent: React.FC = () => {

  const history = useHistory()

  let redirectBackHome = () => history.push("/")

  return <button onClick={redirectBackHome}>Important button</button>;
}

It took me quite some time to fix this issue. I hope my blogpost will save someone's time.