Reactjs – React-Router: Why is the useHistory undefined in react?

react-hooksreact-router-domreactjs

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

Best Answer

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.