Open cossack910 opened 1 year ago
参考 https://reffect.co.jp/react/react-router-6/
main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { BrowserRouter } from "react-router-dom"; ←ここでインポート
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<BrowserRouter> ←Appを囲む
<App />
</BrowserRouter>
</React.StrictMode>
);
App.tsx
...
<Route path="/page1" element={<Page1 />}>
<Route path="detail" element={<Page1Detail />} />
</Route>
...
Outletの設定 ネストした子コンポーネントの表示するには親コンポーネントにこの設定を行う
親コンポーネント /route/Page1.tsx
import { Outlet } from "react-router-dom"; ←これインポート
export const Page1: React.FC = () => {
return (
<div>
<h1>ページ1</h1>
<Outlet /> ←これ
</div>
);
};
export default Page1;
子コンポーネント /route/Deatil/Page1Detail
export const Page1Detail: React.FC = () => {
return (
<div>
<h1>page1の詳細</h1>
</div>
);
};
export default Page1Detail;
パスパラメーター
import { useParams } from "react-router-dom";
export const UrlParameter = () => {
const { id } = useParams();
...
クエリパラメーター
import { useLocation } from "react-router-dom";
export const UrlParameter = () => {
const { search } = useLocation();
const query = new URLSearchParams(search);
...
<p>queryパラメータ {query.get("name")}</p>
...
<Link to={{ pathname: "detail" }} state={arr}>
detail
</Link>
Page1Detail.tsx https://github.com/cossack910/reactAd/blob/629159459a876e44d38e21f8d632b78b54e98254/app/src/Detail/Page1Detail.tsx#L10
import { useLocation } from "react-router-dom";
export const Page1Detail = () => {
const { state } = useLocation();
return (
<div>
<h1>page1の詳細</h1>
<p>{state}</p>
</div>
);
};
export default Page1Detail;
navigateのページ遷移
import { useLocation, useNavigate } from "react-router-dom";
export const Page1 = () => {
const navigate = useNavigate();
const onClickDeatil = () => navigate("/detail"); //パス
return (
<div>
<h1>ページ1</h1>
<Link to={{ pathname: "detail" }}>
detail
</Link>
<br />
<button onClick={onClickDeatil}>
DetailButton
</button>
</div>
);
};
export default Page1;
react-routerインストール(ver6)
package.json
types