bdux-react-router
v18.0.4
Published
A Bdux Addon
Downloads
13
Maintainers
Readme
Bdux React Router
Want to achieve
- Record and travel back in the history of URL changes with bdux-timetravel.
- Utilise routing library react-router.
Installation
To install as an npm package:
npm install --save bdux-react-router
Usage
import React from 'react'
import { Router, Route, createLocationHistory } from 'bdux-react-router'
import { LocationAction, LocationStore } from 'bdux-react-router'
import { createUseBdux } from 'bdux'
const useBdux = createUseBdux({
location: LocationStore
}, [
// start listening to browser history.
LocationAction.listen
])
function App(props) {
const { state } = useBdux(props)
const { location } = state
return (
<Router history={createLocationHistory(location)}>
<Route
component={Page}
path="/path"
/>
</Router>
)
}
export default React.memo(App)
Browser history changes are captured in LocationAction
to LocationStore
then into Router
. The router component itself does not listen to browser history directly. This data flow ensures routing can be recorded and replayed by middleware.
Link
Link component is a convenient way to create a simple anchor element to update browser history through LocationAction
without reloading the entire page.
<Link to="/path">Text</Link>
For more complex scenarios, create components to work with LocationAction.push
or LocationAction.replace
. Underneath these two functions use library history. Refer to their documentation about location for details.
import React, { useCallback } from 'react'
import LocationAction from 'bdux-react-router'
import { useBdux } from 'bdux'
function Button(props) {
const { dispatch } = useBdux(props)
const handleClick = useCallback(() => {
dispatch(LocationAction.push({
pathname: '/path'
}))
}, [])
return (
<button onClick={handleClick} />
)
}
export default React.memo(Button)