---
# System prepended metadata

title: '[React Router] 基礎配置'
tags: [react-router, React]

---

## 簡介

## 安裝
撰寫筆記當下的版本為 ^6.22.3
```bash=
npm install react-router-dom
```

## 導入react-router
預設使用vite建立專案的情況下

1. main.jsx：
```jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter> // 包住App
  </React.StrictMode>,
);
```
- react-router 提供以下 router components：
    常用的：
    - `Router`：最基礎的
    - `BroswerRouter`：History API
    
    沒用過：
    - `HashRouter`r：Hash(#)
    - `MemoryRouter`：內存、測試
    - `NativeRouter`：React Native
    - `StaticRouter`：SSR

2. App.jsx：定義路由
```jsx
import { Routes, Route } from 'react-router-dom';
import Root from './routes/Root';
import Home from './routes/Home';
import About from './routes/About';

const App = () => {
  return (
    <>
      <Routes>
        <Route element={<Root />}>
          <Route index element={<Home />} />
          <Route path="/about" element={<About />} />
        </Route>
      </Routes>
    </>
  );
};

export default App;
```
3. Root.jsx：
```jsx
import { Outlet } from 'react-router-dom';

const Root = () => {
  return (
    <div>
      <Outlet />
    </div>
  );
};

export default Root;
```

<!--  
## 疑問
- [ ] root.jsx是必要檔案嗎？
-->