14

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
  • 3,093
  • 2
  • 20
  • 22
MiguelParkour
  • 151
  • 1
  • 1
  • 4
  • 7
    `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
  • Does this answer your question? [Cannot read property 'history' of undefined (useHistory hook of React Router 5)](https://stackoverflow.com/questions/58220995/cannot-read-property-history-of-undefined-usehistory-hook-of-react-router-5) – SuleymanSah Jul 12 '21 at 11:19

1 Answers1

12

You are adding the Router to the DOM with <Router>...</Router> in the same component you are using useHistory.

useHistory will work only on child components but it won't work on parent component or the component itself.

You have to move the <Router>...</Router> wrapping of the component one level up. You can do that in the app.js:

App.js



import { BrowserRouter as Router } from 'react-router-dom'; 

function App() {
  return (
    <Router>
      <div className="App">
      </div>
    </Router>
  );
}

export default App;

component.js


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


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

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

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

export default withRouter(HomeButton);

This worked for me.

ayesha ayub
  • 121
  • 1
  • 4