LoginSignup
1

More than 3 years have passed since last update.

nanorouterでReactのルーティング処理を簡単に自作する

Last updated at Posted at 2020-03-09

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は機能が少なくて使いやすいが、設計がイミュータブルじゃないのが若干微妙。
パスに該当するデータを返す関数みたいな動きをするルータがあればいいんだが。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1