nanorouterでReactのルーティング処理を簡単に自作するの続き。
今度は前回作ったやつをHooks化して、さらにHistoryパッケージを統合して遷移イベントのフックも行う。
import React from 'react';
import nanorouter from "nanorouter"
import { createBrowserHistory } from 'history'
export const useRouter = (routes) => {
const history = React.useRef(createBrowserHistory())
const [currentPath, setCurrentPath] = React.useState(history.current.location.pathname)
React.useEffect(() => {
history.current.listen((location, action) => {
setCurrentPath(location.pathname)
})
}, [])
const nextComponent = React.useRef(null)
const router = nanorouter({ default: "/" })
Object.keys(routes).forEach(path => {
router.on(path, param => { nextComponent.current = routes[path] })
})
router.emit(currentPath)
return [history.current, nextComponent.current]
}
使う側のインタフェースはこんな感じになる。
import React from 'react'
import { useRouter } from './Route'
import { PageA } from './PageA'
import { PageB } from './PageB'
function App() {
const [history, router] = useRouter({
'/hello': <PageA />,
'/world': <PageB />,
})
return (
<div className="container">
{router}
<button onClick={() => history.push("/world")}>world</button>
<button onClick={() => history.push("/hello")}>hello</button>
</div>
)
}
export default App;