接下來 3 天的 React Router 練習,請 fork 這個專案來練習。 [專案 GitHub 連結](https://github.com/hexschool/2023-react-daily-task-router) ### React Router 介紹 React Router 提供元件和 Hook,可以直接使用它來進行頁面路由的開發。 以下介紹基本常用的元件: 1. `<NavLink>`:和我們常見的 ``<a href="#"></a>`` 的作用是類似的,但會處理掉預設行為,並導向對應的路由。而在 React Router 中 `<NavLink>` 與 `<Link>` 都是連結功能,不一樣的地方在於當這個 NavLink 與目前的 URL 符合時,會自動加上 active class。 舉例: ```jsx= <NavLink to="/about"> <p>關於我們</p> </NavLink> ``` 2. `<Route>`:設置相對應的路徑。當路徑符合目前的 URL,則會渲染指定的 元件。例如: ```jsx= <Route path="/about" element={<About />} /> ``` 3. `<Routes>`: `<Route>` 必須使用`<Routes>` 來包住 ,每當 URL 更改時,`<Routes>` 會查找所有children,並找到對應的 `<Route>` 設定來顯示要出現的元件。 例如: ```jsx= <Routes> <Route path="/about" element={<About />} /> <Routes> ``` 4.`<BrowserRouter>` or `<HashRouter>`:通常會用在最外層,讓包在裡面的 Child Component 可以使用路由。 - HashRouter: 頁面路徑最前面會有個「#」,例如: `/#/about`。這代表路由會由前端進行模擬,像是部署在 GitHub Pages 上就建議採用此模式。 - BrowserRouter: 頁面路徑不會有井字,例如: `/about`。路由會需要後端協助處理,否則在 refresh 後就會出現 404,因為實際上 build 出來是沒有 about.html(只有 index.html) ### 補充 有時候我們輸入一些不存在的路由,會看到 404 Not Found 的頁面,這邊在 Router 設定也可以做到唷 ```jsx <Route path="*" element={ <main style={{ padding: "1rem" }}> <p>There's nothing here!</p> </main> } /> ``` 透過 `*` 的設置,當輸入的路由不符合任何已存在的路由,就會出現對應的 element。 [No Match Route 文件](https://reactrouter.com/6.28.0/start/faq#how-do-i-add-a-no-match-404-route-in-react-router-v6) ## 題目 請撰寫 Routes, Route 的部分,建立 register(註冊), login(登入), todo(待辦事項) 三個頁面路由,讓上方的 Nav 選單可切換到各頁面。 ## 回報流程 將答案寫在專案的 App.js 中,並將完成的內容放到 GitHub 上,複製 App.js 連結貼至底下回報就算完成了喔! 解答位置請參考下圖(需打開程式碼的部分觀看) ![](https://i.imgur.com/vftL5i0.png) <!-- 解答: ``` <Routes> <Route path="/register" element={<Register />} /> <Route path="/login" element={<Login />} /> <Route path="/todo" element={<Todo />} /> </Routes> ``` --> 回報區 --- | # | Discord | GitHub / 答案 | |:-:|:--------------:|:-------------------------------------------------------------------:| | 1 |Noy(Toad)| [Github](https://github.com/MochiTree/2023-react-daily-task-router/blob/main/src/App.jsx)| | 2 | LinaChen | [GitHub](https://github.com/Lina-SHU/2025-react-daily-task-router/blob/main/src/App.jsx) | | 3 | 泊岸 | [GitHub](https://github.com/oriascrius/2023-react-daily-task-router/blob/main/src/App.jsx) | | 4 | Kaya | [GitHub](https://github.com/kayaribi/2023-react-daily-task-router/blob/main/src/App.jsx) | |5|邵|[GitHub](https://github.com/oxfoxlion/ReactRouter_DailyTask/blob/main/src/App.jsx)| |6|Johnson|[GitHub](https://github.com/tttom3669/2023-react-daily-task-router/blob/main/src/App.jsx)| |7|Rogan|[GitHub](https://github.com/hoganalin/2025-react-daily-task-router/blob/main/src/App.jsx)| | 8 | Sonia |[GitHub](https://github.com/yujouwu/2023-react-daily-task-router/blob/main/src/App.jsx)| | 9 | jinliu214 | [GitHub](https://github.com/jinliu214/2025-react-daily-task-router/blob/main/src/App.jsx) | ```markdown= | 00 | user | [GitHub]() | ```