nanorouterというURLパスのパターンマッチングだけをやってくれるライブラリがあるので、それを使ってReactアプリケーションのルーティング部分を自作します。History APIとかそんなものは知らん。
まずはルーティングの実装。
nextComponent
変数がイミュータブルじゃないのが気になってしょうがない。
Route.js
import React from 'react';
import nanorouter from "nanorouter"
export const Route = routes => {
const router = nanorouter({ default: '/' })
let nextComponent = null
Object.keys(routes).forEach(path => {
router.on(path, param => { nextComponent = routes[path] })
})
router.emit(window.location.pathname)
return (
<div className="container">
{nextComponent}
</div>
)
}
Routeを使うAppコンポーネント
App.js
import React from 'react'
import { Route } from './Route'
import { PageA } from './PageA'
import { PageB } from './PageB'
function App() {
return Route({
'/hello': <PageA />,
'/world': <PageB />,
})
}
export default App;
ルーティングするページふたつ
PageA.js
import React from 'react';
export const PageA = () => {
return (
<div>This is page A</div>
)
}
PageB.hs
import React from 'react';
export const PageB = () => {
return (
<div>This is page B</div>
)
}
nanorouterは機能が少なくて使いやすいが、設計がイミュータブルじゃないのが若干微妙。
パスに該当するデータを返す関数みたいな動きをするルータがあればいいんだが。