Skip to main content

[note] React Reach Router

@reach/router @ official website

Install#

npm install @reach/router

Usage with TypeScript#

Usage with TypeScript @ reach/router

$ npm install @types/reach__router --save-dev

使用 @reach/router 提供的 RouteComponentProps 搭配 React.FC 來定義 Component 的型別:

import { Router, RouteComponentProps, Link } from "@reach/router"
const Home = React.FC<RouteComponentProps> => <div>Home</div>

若想取得路由中的參數資料,可以 extends RouteComponentProps 來定義該元件的 props:

// ./views/Book.tsx
import React from 'react';
import { RouteComponentProps } from '@reach/router';
interface BookProps extends RouteComponentProps {
bookId?: string;
}
const Book: React.FC<BookProps> = (props) => {
return <h1>Book: {props.bookId}</h1>;
};
export default Book;

路由設定的地方:

// ./App.tsx
import { Book } from './views';
import { Link, Router } from '@reach/router';
function App() {
return (
<div className="App">
<Router>
<Book path="/book/:bookId" />
</Router>
</div>
);
}
export default App;

Navigate(轉址)#

navigate @ react/router tutorial

import { Router, Link, navigate } from '@reach/router';
navigate(`/invoices/${id}`);
// 或者可以直接從元件的 props 取得 navigate
props.navigate(id);

通常是使用者提交表單後,進行轉址使用。

其他#

Index Routes#

index route 和其他路由沒有什麼不同,都是單純的 React 元件,主要是當作 nested route 的 index 頁(沒有任何 nested route 匹配到時):

<Router>
<Electronics path="/electronics">
<ElectronicsIndex path="/" /> // /electronics/
<Mobile path="mobile" /> // /electronics/mobile
<Desktop path="desktop" /> // /electronics/desktop
<Laptop path="laptop" /> // /electronics/laptop
</Electronics>
</Router>

Default Route(404 Not Found)#

Default Route 一般是用來作為 404 Not Found 頁面:

<Router>
<NotFound default />
{/*...*/}
</Router>
Last updated on