yarn create vite {app_name} --template react-ts
.
├── index.html
├── package.json
├── public
│ └── vite.svg
├── src
│ ├── App.css
│ ├── App.tsx #📝
│ ├── assets
│ │ └── react.svg
│ ├── index.css
│ ├── main.tsx
│ ├── pages
│ │ ├── top
│ │ │ └── index.tsx #📝
│ │ └── users
│ │ └── [id]
│ │ └── index.tsx #📝
│ └── vite-env.d.ts
├── tsconfig.json
├── tsconfig.node.json
├── vite.config.ts
└── yarn.lock
yarn add react-router-dom
import { BrowserRouter, ParamParseKey, Route, Routes, useParams } from "react-router-dom";
import User from "./pages/users/[id]";
import "./App.css";
import Top from "./pages/top";
export const PATHS = {
TOP: "/",
ABOUT: "/about",
USERS_ID: "/users/:id",
} as const;
// これでクエリパラメータの id が取り出せる
export const useParamsUsersId = useParams<ParamParseKey<typeof PATHS.USERS_ID>>;
function App() {
return (
<BrowserRouter>
<Routes>
<Route path={PATHS.TOP} element={<Top />} />
<Route path={PATHS.ABOUT} element={<div>About</div>} />
<Route path={PATHS.USERS_ID} element={<User />} />
<Route path="*" element={<div>Not Found</div>} />
</Routes>
</BrowserRouter>
);
}
export default App;
import { generatePath } from "react-router-dom";
import { PATHS } from "../../App";
function Top() {
return (
<div>
<h4>Top</h4>
{/* generatePath で :id に代入できる */}
<a href={generatePath(PATHS.USERS_ID, { id: "1" })}>User 1</a>
<br />
{/* これはエラー */}
{/* Argument of type '{ userId: string; }' is not assignable to parameter of type '{ id: string; }'.
Object literal may only specify known properties, and 'userId' does not exist in type '{ id: string; }' */}
<a href={generatePath(PATHS.USERS_ID, { userId: "2" })}>User 2</a>
<br />
<a href={generatePath(PATHS.USERS_ID, { id: "3" })}>User 3</a>
</div>
);
}
export default Top;
import { useParamsUsersId } from "../../../App";
function User() {
const { id } = useParamsUsersId();
return (
<div>
<h4>User</h4>
<p>id: {id}</p>
</div>
);
}
export default User;