Day 33/100 #100DaysOfCode
Hôm nay tìm hiểu về react-router-dom V6, thấy ae đang dùng cái này nhiều nên tìm hiểu xem sao.
$ npm install react-router-dom@6
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
+ path : cung cấp đường dẫn trỏ đến Component
+ index: ta có thể rán cho một Component hiển thị mặt định "default" khi chạy chương trình lên
+ element : cung cấp Component cần dùng
Trong Route ta có thể cấu hình child Component cho nó như sau:
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
- Parent "Teams"
- Child "Teams:teamId" : ta dùng useParams() để lấy tham số teamId trong Child component nhé
Oh, quên để hiển thị được child ta cần đến Outlet nhé
import {Outlet} from "react-router-dom";
const Teams = ()=>{
return (
<div>
<h1>Parent</h1>
<Outlet />
</div>
)
}
import {useParams} from "react-router-dom";
const Team = ()=>{
const {teamId} = useParams()
return (
<div>
<h2>Child</h2>
<p>Id : {teamId} </p>
</div>
)
}
+ Link : dùng để chuyển qua lại các component nó như thẻ <a href=""/>, có điều nó dùng Link để cấu hình đường dẫn Route
<Link to="/home">Home</Link> <Link to="teams/12">Teams:teamId</Link>
+ Nếu bạn muốn chuyển hướng đến Component khác, sau hành động submit form hay gì gì đó, sử dụng useNavigate
import React from 'react'
import { useNavigate } from "react-router-dom";
export default function NewTeamForm() {
const teamId = 1;
let navigate = useNavigate();
return (
<div>
NewTeamForm
<button onClick={()=>{
navigate(`/teams/${teamId}`);
}}>Go to Teams:teamId</button>
</div>
)
}
+ Lấy tham số trên đường URL route, sử dụng useParams()
//"https://example.com/teams/12"
<Route path="teams/:teamId" element={<Team />} />
//in component Team
let params = useParams();
console.log(params.teamId)
//or
const {teamId} = useParams();
+ Sử dụng path ="*" trên đường dẫn Route, khi URL không được cung cấp đúng với cầu hình Route trong ứng dụng , ta có thể trỏ đến component mà ta cần muốn thị
<Route path="*" element={<NotFount />}
- Nếu bạn muốn lấy mọi thứ phía sau của một đường link cụ thể cũng được
<Route path="/teams/:teamId/*" element={<Team />}
Có thể xem thêm tại đây :
+ Link : URL ROUTER IN REACT
+ Link :https://reactrouter.com/docs/en/v6/getting-started/installation