10

I have this. It is exactly the same as it says in the documentation. I think the react-router-dom module is fine because in other components the BrowserRouter, Router and Link work for me

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

export default function HomeButton() {
  let history = useHistory()

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

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

when I click the button this happens

TypeError: Cannot read property 'push' of undefined

I am newbie in reactjs please help, and thanks

Nora
  • 2,688
  • 1
  • 19
  • 22
MiguelParkour
  • 111
  • 1
  • 4
  • 2
    `useHistory` won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set. `useHistory` will work on any child component or components which your have declared in your but it won't work on 's parent component or component itself – Jawad ul hassan Jun 27 '20 at 21:02

1 Answers1

21
  1. Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one.

  2. The same error can be thrown when one of them(Router and the useHistory hook) are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them,

sidverma
  • 808
  • 7
  • 18