Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router: Why is the useHistory undefined in react? [duplicate]

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

like image 214
MiguelParkour Avatar asked Jun 27 '20 19:06

MiguelParkour


People also ask

Why is useHistory undefined?

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 you have declared in your Router but it won't work on Router's parent component or Router component itself.

Is useHistory deprecated?

The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.

What can we use instead of useHistory?

6, useHistory doesn't exist anymore, instead we have a useNavigate hook. This useNavigate hook gives us a navigate object and function, and this navigate function can be executed to navigate somewhere else.


Video Answer


1 Answers

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.

like image 151
ayesha ayub Avatar answered Sep 18 '22 12:09

ayesha ayub