1 minute read

学んだこと

URL パラメータを扱う場合

  • ルートのパスに/:idなどパラメータを設定することで各種パラメータを受け取れるようになる。

実際に試してみた

  • UrlParameter
    • ルートで設定するパラメータを定義
    • 今回 UrlParameter にて id を受け取りたいため、/:idを設定している
import { Page2 } from '../Page2';
import { UrlParameter } from '../UrlParameter';
export const page2Routes = [
  {
    path: '/',
    exact: true,
    children: <Page2 />,
  },
  {
    path: '/:id',
    exact: false,
    children: <UrlParameter />,
  },
];

  • Page2.jsx
    • Page2 のページ処理を記述
    • Link にて、URL パラメータを設定
      • /page2/9999の 9999 が/:idに該当する。
      • URLParameter に遷移することで 9999 が URLParameter に渡る。
import { Link } from 'react-router-dom';

export const Page2 = () => {
  return (
    <div>
      <h1>Page2ページです。</h1>
      <Link to="/page2/9999">URL Parameter</Link>
    </div>
  );
};
  • UrlParameter.jsx
    • 受け取った id を表示した。
    • react-router-domuseParamsを利用し、id を取得
import { useParams } from 'react-router-dom';
export const UrlParameter = () => {
  const { id } = useParams();
  return (
    <div>
      <h1>UrlParameterページです</h1>
      <p>パラメータは{id}です</p>
    </div>
  );
};

  • Router.jsx
    • 大元のルート設定を記述
    • Page2Router 内にあるpage2Routesをループし、各種ページ設定を行っている。
import { Switch, Route } from 'react-router-dom';

import { Page2 } from '../Page2';
import { Home } from '../Home';
import { page1Routes } from './Page1Routes';
import { page2Routes } from './Page2Routes';

export const Router = () => {
  return (
    <Switch>
      <Route exact path="/">
        <Home />
      </Route>
      <Route
        path="/page1"
        render={({ match: { url } }) => (
          <Switch>
            {page1Routes.map((route) => (
              <Route
                key={route.path}
                exact={route.exact}
                path={`${url}${route.path}`}
              >
                {route.children}
              </Route>
            ))}
          </Switch>
        )}
      ></Route>
      <Route
        path="/page2"
        render={({ match: { url } }) => (
          <Switch>
            {page2Routes.map((route) => (
              <Route
                key={route.path}
                exact={route.exact}
                path={`${url}${route.path}`}
              >
                {route.children}
              </Route>
            ))}
          </Switch>
        )}
      ></Route>
    </Switch>
  );
};

Tags:

Updated: