Reactでルーティングを設定する

React


Reactでルーティングをする場合
react-route-domを使用します。

webアプリの場合
react-router-dom

モバイルアプリ用
react-router-native

それぞれのコアである
react-routerがありますが、今回はreact-router-domを使用します。
間違えた物を使わないよう注意です。

下記コマンドでインストールしましょう。

npm install react-router-dom

次にルーティングして、渡し値を渡すサンプルですが、公式が優秀です。

まずは公式HPを参照して

https://reactrouter.com/web/

この中でQuery Parametaersのサンプルを実装します。
使用するのは

  • index.html
  • index.js
  • exmaple.js

になります。
package.jsonもありますが、reactをインストールして上記でreact-router-domをインストールしていれば大丈夫です。
公式からコードをもらいつつ、少し解説

indexは基本他からjs等を読み込むだけです。基本は外部のjsに書いてます。

index.html

<div id="root"></div>

index.js

/**
  This CodeSandbox has been automatically generated using
  `codesandboxer`. If you're curious how that happened, you can
  check out our docs here: https://github.com/codesandbox/codesandboxer

  If you experience any struggles with this sandbox, please raise an issue
  on github. :)
*/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './example';

ReactDOM.render(
<App />,
document.getElementById('root')
);

example.js

import React from "react";
import {
  BrowserRouter as Router,
  Link,
  useLocation
} from "react-router-dom";

// React Router does not have any opinions about
// how you should parse URL query strings.
//
// If you use simple key=value query strings and
// you do not need to support IE 11, you can use
// the browser's built-in URLSearchParams API.
//
// If your query strings contain array or object
// syntax, you'll probably need to bring your own
// query parsing function.

export default function QueryParamsExample() {
  return (
    <Router>
      <QueryParamsDemo />
    </Router>
  );
}

// A custom hook that builds on useLocation to parse
// the query string for you.
function useQuery() {
  return new URLSearchParams(useLocation().search);
}

function QueryParamsDemo() {
  let query = useQuery();

  return (
    <div>
      <div>
        <h2>Accounts</h2>
        <ul>
          <li>
            <Link to="/account?name=netflix">Netflix</Link>
          </li>
          <li>
            <Link to="/account?name=zillow-group">Zillow Group</Link>
          </li>
          <li>
            <Link to="/account?name=yahoo">Yahoo</Link>
          </li>
          <li>
            <Link to="/account?name=modus-create">Modus Create</Link>
          </li>
        </ul>

        <Child name={query.get("name")} />
      </div>
    </div>
  );
}

function Child({ name }) {
  return (
    <div>
      {name ? (
        <h3>
          The <code>name</code> in the query string is "{name}
          "
        </h3>
      ) : (
        <h3>There is no name in the query string</h3>
      )}
    </div>
  );
}