LoginSignup
1
0

More than 3 years have passed since last update.

nanorouterで作った自作のルーティングをHooks化する

Last updated at Posted at 2020-03-21

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;

1
0
0

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
0