React Router နဲ့ Routing
19.3
URL တစ်ခုစီမှာ ဘယ် screen ပြမလဲ သတ်မှတ်ပါ။ အရေးကြီးတဲ့ screen တိုင်းကို bookmark လုပ်လို့ရ၊ share လို့ရတဲ့ URL ပေးပါ။
Code စမ်းလို့ရတဲ့ သင်ခန်းစာ ဖွင့်ရန်
ဒီစာမျက်နှာမှာ
Links နဲ့ Routes ထည့်ပါ
react-router ကို install လုပ်ပြီး route tree ကို BrowserRouter နဲ့ wrap လုပ်ပါ။ Routes က ကိုက်ညီတဲ့ route ရွေးပြီး NavLink က လက်ရှိ active link ကို သိစေပါတယ်။ /products/:id လို path က product ID ကို useParams နဲ့ ယူလို့ရစေပါတယ်။
import React from "react";
import { BrowserRouter, NavLink, Route, Routes, useParams } from "react-router";
function Product() {
const { id } = useParams();
return <h1>Product {id}</h1>;
}
export default function App() {
return (
<BrowserRouter>
<nav>
<NavLink to="/" end>Home</NavLink>{" "}
<NavLink to="/products/42">Pen</NavLink>
</nav>
<Routes>
<Route path="/" element={<h1>Inventory</h1>} />
<Route path="/products/:id" element={<Product />} />
<Route path="*" element={<h1>Page not found</h1>} />
</Routes>
</BrowserRouter>
);
}
Page URL ကို တိုက်ရိုက် ဖွင့်လို့ရအောင် လုပ်ပါ
User က /products/42 ကို reload လုပ်ရင် request က host ဆီ အရင်ရောက်ပါတယ်။ Client page paths တွေအတွက် index.html ကို fallback ပြန်ပေးအောင် သတ်မှတ်ပါ။ API နဲ့ asset routes တွေကို သီးသန့် ဆက်ထားပါ။ Link၊ direct reload၊ Back ခလုတ်နဲ့ မရှိတဲ့ URL ကို စမ်းပါ။ Client ဘက်က not-found screen က server HTTP status မသတ်မှတ်ပေးပါဘူး။
# Nginx: inside the server block for the SPA
location /products/ {
try_files $uri $uri/ /index.html;
}
# Keep existing /api/ and asset locations separate.