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
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.
The use of history and useHistory is deprecated and should be replaced with the useNavigate hook.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With