react-router-use-history
useHistory
in react router v6
Install
pnpm add react-router-use-history
Usage
createBrowserRouter
and <RouterProvider />
(Data Browser Router)
Router created with React router >=
v6.4.0
import { useHistory } from 'react-router-use-history'
function Page() {
const history = useHistory()
// ...
history.push('/a')
}
<BrowserRouter />
(Legacy Browser Router)
Router created with React router >=
v6.0.0
-
Replace
BrowserRouter
:+import { BrowserRouter } from 'react-router-use-history' -import { BrowserRouter } from 'react-router-dom' function Root() { return ( <BrowserRouter> {/* ... */} </BrowserRouter> ) }
-
Enjoy
useHitory
:import { useHistory } from 'react-router-use-history' function Page() { const history = useHistory() // ... history.push('/a') }
Advanced usage
useHistorySelector
history
selector for deep selection value
import { useHistorySelector } from 'react-router-use-history'
function Page() {
const pathname = useHistorySelector(h => h.location.pathname)
}
history
outside of react router
Custom You can define your own history
outside of the react router :
pnpm add history
-
Create independent
history
// history.ts import { createBrowserHistory } from 'history' export const history = createBrowserHistory() // or // import { createBrowserHistory } from '@remix-run/router' // export const history = createBrowserHistory({ v5Compat: true })
-
Replace
<BrowserRouter>
and injecthistory
instanceimport { BrowserRouter } from 'react-router-use-history' import { history } from './history' function Root() { return ( <BrowserRouter history={history}> {/* ... */} </BrowserRouter> ) }
-
Then you can use
history
anywhere// anywhere.ts import { history } from './history' history.push('/page')
License
MIT