react-router-use-history
v1.1.0
Published
useHistory api in react router v6
Downloads
476
Maintainers
Readme
react-router-use-history
useHistory
in react router v6
Install
pnpm add react-router-use-history
Usage
Router created with createBrowserRouter
and <RouterProvider />
(Data Browser Router)
React router >=
v6.4.0
import { useHistory } from 'react-router-use-history'
function Page() {
const history = useHistory()
// ...
history.push('/a')
}
Router created with <BrowserRouter />
(Legacy Browser Router)
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)
}
Custom history
outside of react router
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