3
2

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 1 year has passed since last update.

Vite×React×TypeScript×React Routerで、URLパラメータを取得して表示するサンプル

Last updated at Posted at 2024-05-28

はじめに

こんにちは!@nyakako13 です。

少し前からReact,TypeScriptの学習をしています。

React Routerにまだ慣れておらず、URLパラメータを取得して表示するための手順がパッと出てこなかったので、備忘録もかねて残します。

前提

react: 18.3.1
react-router-dom: 6.23.1

必要な手順

  1. Viteプロジェクトのセットアップ
  2. React Routerの設定
  3. URLパラメータを取得して表示するコンポーネントの作成

1. Viteプロジェクトのセットアップ

Viteを使用して新しいReactプロジェクトを作成します。

shell
npm create vite@latest my-react-app --template react-ts
cd my-react-app
npm install

React Routerをインストールします。

shell
npm install react-router-dom

2. React Routerの設定

src/main.tsx ファイルを編集して、React Routerを設定します。(Routerは別ファイルで分けることも多いと思いますが、今回は最小構成の為、App.tsxで直接ルーティングします。)

localhost/cards/[parameter]でアクセスした時に、そのURLパラメータ([parameter]の部分)だけを表示する簡単なサンプルです。

src/main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import App from "./App.tsx";
import { Card } from "./components/Card.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <BrowserRouter>
	  <Routes>
		<Route path="/" element={<App />} />
		<Route path="cards/:id" element={<Card />} />
	  </Routes>
	</BrowserRouter>
  </React.StrictMode>

3. URLパラメータを取得して表示するコンポーネントの作成

Card コンポーネント(URLパラメータを取得して表示するコンポーネント)を作成し、URLからパラメータを取得して表示します。

src/components/Card.tsx
import { FC } from "react";
import { useParams } from "react-router-dom";

export const Card: FC = () => {
  const { id } = useParams<{ id: string }>();

  return (
    <div>
      <p>{id}</p>
    </div>
  );
};

動作確認

shell
npm run dev

ブラウザでアクセスして表示の確認ができました。
スクリーンショット 2024-05-28 8.52.25.png

完成したディレクトリ構成

my-react-app/
├── node_modules/
├── public/
├── src/
│   ├── assets/
│   ├── components/
│       ├── Card.tsx
│   ├── App.tsx
│   ├── main.tsx
│   └── vite-env.d.ts
├── .gitignore
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

感想

reactでURLから特定のパラメータを簡単に取得したい時はuseParams

記事に残した方が身に付く実感がある&次に同じことやるとき自分でも探しやすいので、どんどん記事にしてアウトプットしていこうと思います!

おわりに

よかったらX(@nyakako13)もフォローしてもらえると嬉しいです。

Qiita100投稿まで残り85!

未経験や浅経験、厳しいと言われている年代でエンジニアへの転職活動されている方、負けずにがんばりましょう!!

参考

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?