mirror of
https://github.com/ershisan99/flashcards-docs.git
synced 2025-12-16 20:59:26 +00:00
86 lines
1.8 KiB
Plaintext
86 lines
1.8 KiB
Plaintext
# Роутинг и защита страниц авторизацией
|
||
|
||
## Роутинг
|
||
|
||
Установим `react-router-dom`:
|
||
|
||
```bash filename="Terminal"
|
||
pnpm i react-router-dom
|
||
```
|
||
|
||
Создадим файл `src/router.tsx`:
|
||
|
||
```tsx filename="src/router.tsx"
|
||
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
|
||
|
||
const router = createBrowserRouter([
|
||
{
|
||
path: '/',
|
||
element: <div>hello</div>,
|
||
},
|
||
])
|
||
|
||
export const Router = () => {
|
||
return <RouterProvider router={router} />
|
||
}
|
||
```
|
||
|
||
Отрендерим его в `App`:
|
||
|
||
```tsx filename="src/App.tsx"
|
||
import { Router } from '@/router'
|
||
|
||
export function App() {
|
||
return <Router />
|
||
}
|
||
```
|
||
|
||
## Защита страниц авторизацией
|
||
|
||
Разделим наши роуты на две переменные - `publicRoutes` и `privateRoutes`:
|
||
|
||
```tsx filename="src/router.tsx"
|
||
import { createBrowserRouter, RouteObject, RouterProvider } from 'react-router-dom'
|
||
|
||
const publicRoutes: RouteObject[] = [
|
||
{
|
||
path: '/login',
|
||
element: <div>login</div>,
|
||
},
|
||
]
|
||
|
||
const privateRoutes: RouteObject[] = [
|
||
{
|
||
path: '/',
|
||
element: <div>hello</div>,
|
||
},
|
||
]
|
||
|
||
const router = createBrowserRouter([...privateRoutes, ...publicRoutes])
|
||
```
|
||
|
||
Создадим компонент `PrivateRoutes`:
|
||
|
||
```tsx filename="src/router.tsx"
|
||
function PrivateRoutes() {
|
||
const isAuthenticated = false
|
||
|
||
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />
|
||
}
|
||
```
|
||
|
||
И обернем им наши privateRoutes:
|
||
|
||
```tsx filename="src/router.tsx"
|
||
const router = createBrowserRouter([
|
||
{
|
||
element: <PrivateRoutes />,
|
||
children: privateRoutes,
|
||
},
|
||
...publicRoutes,
|
||
])
|
||
```
|
||
|
||
Теперь когда `isAuthenticated` будет `false`,
|
||
при переходе на `/` мы будем перенаправлены на `/login`.
|