When I am using the history.push function, it always returns this error
TypeError: history is undefined
import React from 'react';
import { useHistory } from 'react-router-dom';
function App() {
let history = useHistory();
function testing() {
history.push("/whatever");
}
return (
<div className="App">
<button onClick={testing}>Test</button>
</div>
);
}
export default App;
My packages:
{
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.1",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
and finally, the error I'm getting:
App
is the first component after your index.js, then you will need to wrap it around a <BrowserRouter>
to use useHistory()
Something like this in your root (index) component:
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
rootElement
);