LoginSignup
225
167

More than 3 years have passed since last update.

React RouterがHooks対応したので使い方を整理する

Last updated at Posted at 2019-09-26

概要

  • ReactRouterがv5.1でHooks対応しました
  • 以前 react-router + React Hooks という記事で use-react-router の使い方を紹介しました
  • ですが、ReactRouter本体がHooks対応したのでこれから作る場合はこの記事のやり方で実装していくことになります

サンプルコード

  • ReactRouterのHooksを使った簡単なサンプルです
mkdir react-router-with-hook
cd react-router-with-hook
yarn init -y
yarn add react react-dom react-router-dom
touch index.html index.js
index.html
<div id="root"></div>
<script src="./index.js"></script>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Route,
  Switch,
  useParams,
  useHistory,
  useLocation,
} from 'react-router-dom';

function Hello() {
  const history = useHistory();
  return (
    <div>
      <h1>Hello</h1>
      <button
        onClick={() => history.push('/hello/react-router?message=hooks#test')}
      >
        Next
      </button>
    </div>
  );
}

function HelloSomeone() {
  const history = useHistory();
  const location = useLocation();
  const { name } = useParams();
  return (
    <div>
      <h1>Hello {name} !</h1>
      <p>pathname: {location.pathname}</p>
      <p>search: {location.search}</p>
      <p>hash: {location.hash}</p>
      <button onClick={() => history.goBack()}>Go Back</button>
    </div>
  );
}

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact>
          <Hello />
        </Route>
        <Route path="/hello/:name" exact>
          <HelloSomeone />
        </Route>
      </Switch>
    </Router>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
  • 以下のコマンドで起動します
npx parcel-bundler ./index.html

demo.gif

コードの説明

useHistory

  • ページ遷移させるときに使うhistoryを取得できます
    • const history = useHistory()
    • history.push('/')history.goBack()といった具合で使います

useLocation

  • 現在のページのURLのpathやqueryなどの情報を取得できます
    • const location = useLocation()
    • location.pathlocation.searchといった具合で使います

useParams

  • URLのパスの中で動的に変化する部分の値を取得できます
    • <Route path="/hello/:name">と定義したページにアクセスした際に
    • const { name } = useParams();とすると:nameの部分の値を取得できます

まとめ

  • Hooksで書けると昔のHOCを使った書き方より見通しがよいですね
  • 一時的に使っていたuse-react-routerと若干仕様は違いますが違和感なく使えそうです
225
167
1

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
225
167