Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
48
Help us understand the problem. What is going on with this article?
@ozaki25

react-router + React Hooks

More than 1 year has passed since last update.

追記(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便利
48
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ozaki25
mdc
”自己研鑽のサイクル”を応援するコミュニティです。外の世界に発信&フィードバックを受け、コミュニティの仲間と共に頑張りましょう。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
48
Help us understand the problem. What is going on with this article?