I am working with a migration project, I do not have much idea about react-router-dom 4.3.1
.
My React version is: React.version '16.14.0'
and the router dom is react-router-dom": "^4.3.1"
. When I use the goBack()
from history getting an error as:
TypeError: (0 , _reactRouterDom.useHistory) is not a function
Code:
import { NavLink, useHistory } from 'react-router-dom';
const goBackToPreviousPage = () => {
const history = useHistory();
history.goBack();
};
<button onClick={goBackToPreviousPage}>
Back to previous page
</button>
The useHistory
hooks was introduced in react-router@5
, as well as useLocation
, useParams
, and useRouteMatch
hooks. react-router@4
and react-router@5
are generally considered to be the same "version". The v4 docs even link to the official v5 docs.
My suggestion if you want to avoid actual major breaking changes (i.e. upgrading to v6 would be a lot of work) and use the useHistory
hook is to simply upgrade from v4 to v5.
Uninstall any existing react-router
and react-router-dom
versions.
npm uninstall --save react-router
npm uninstall --save react-router-dom
Install react-router-dom
v5 latest. RRD re-exports all of react-router
so there's no need to have both installed as dependencies.
npm install --save react-router-dom@5
Note that the code still needs to follow the Rules of Hooks. The useHistory
hook cannot be called in the callback, but must be called in the React Function component body.
import { NavLink, useHistory } from 'react-router-dom';
const Component = () => {
const history = useHistory();
...
const goBackToPreviousPage = () => {
history.goBack();
};
...
return (
...
<button onClick={goBackToPreviousPage}>
Back to previous page
</button>
...
);
}
Or more succinctly:
const history = useHistory();
...
<button onClick={history.goBack}>
Back to previous page
</button>