59
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

react-router + React Hooks

Last updated at Posted at 2019-02-19

追記(2019/9/26)

概要

  • react-routerをHOCではなくHooksを使って実装したメモ
  • use-react-routerを使う

手順

  • プロジェクト作成とモジュールのインストール
mkdir react-router-with-hook
cd react-router-with-hook
yarn init -y
yarn add react react-dom react-router-dom use-react-router
  • index.htmlの作成
index.html
<div id="root"></div>
<script src="./index.js"></script>
  • index.jsの作成
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import useReactRouter from 'use-react-router';

function Hello() {
  const { history, location, match } = useReactRouter();
  return (
    <div>
      <h1>HelloWorld</h1>
      <p>{`pathname: ${location.pathname}`}</p>
      <button onClick={() => history.push('/react')}>Next</button>
    </div>
  );
}

function HelloReact() {
  const { history, location, match } = useReactRouter();
  return (
    <div>
      <h1>HelloReact</h1>
      <p>{`pathname: ${location.pathname}`}</p>
      <button onClick={() => history.push('/')}>Next</button>
    </div>
  );
}

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" component={Hello} exact />
        <Route path="/react" component={HelloReact} exact />
      </Switch>
    </Router>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
  • 簡単に説明しておくと、HelloコンポーネントとHelloReactコンポーネントがあり前者が/が後者が/reactにルーティングされるようにしている
  • コンポーネント内で以下のようにuseReactRouter()を使うだけでhistorylocationといった情報を取ることができる
const { history, location, match } = useReactRouter();

デモ

  • 以下のコマンドで起動できる
npx parcel-bundler ./index.html

demo.gif

まとめ

  • Hooksのおかげでreact-routerを使うのもよりお手軽になった
  • use-react-router便利
59
47
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
59
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?