Files
flashcards-docs/pages/lesson-3/chapter-1.ru.mdx
2023-08-05 15:01:26 +02:00

86 lines
1.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Роутинг и защита страниц авторизацией
## Роутинг
Установим `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`.