Router, Routes, Route

김종민·2022년 9월 22일
0

Nuber-Client

목록 보기
7/21

들어가기
Front에서 사용될 route를
한꺼번에 정리 한다.
react-router-dom
페이지를 이동 및, 페이지의 주소 관리


npm i react-router-dom
npm i @types/react-router-dom
npm i @types/react-dom ??

react-router-dom이 upgrade 되면서
---Router
-----Routes
-------Route
구조로 바뀜..

react-router-dom 홈페이지를 항상 참조할 수 있데 한다.

1. src/route/logged-out-router.tsx

import React from 'react'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
///import 할때는, BrowserRouter as 로 import함.

import { NotFound } from '../pages/404'
///없는 주소로 찍혔을때, 보여지는 page
///Router-Routes-Route구조임

import { CreateAccount } from '../pages/create-account'
import { Login } from '../pages/login'

export const LoggedOutRouter = () => {
  return (
    <Router>
      <Routes>
        <Route path="/signup" element={<CreateAccount />} />
        <Route path="/" element={<Login />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </Router>
  )
}
///path가 /는 홈, *는 그외 모든 page

2. src/route/logged-in-router.tsx

import React from 'react'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
///BrowserRouter as 로 import해야함.

import Header from '../components/header'
import { useMe } from '../hooks/useMe'
import { NotFound } from '../pages/404'
import Category from '../pages/client/category'
import RestaurantDetail from '../pages/client/restaurantDetail'
import Restaurants from '../pages/client/restaurants'
import Search from '../pages/client/search'
import AddDish from '../pages/owner/add-dish'
import AddRestaurant from '../pages/owner/add-restaurant'
import MyRestaurant from '../pages/owner/my-restaurant'
import MyRestaurants from '../pages/owner/my-restaurants'
import ConfirmEmail from '../pages/user/confirm-email'
import EditProfile from '../pages/user/edit-profile'

///route가 user의 role에 따라 path가 바뀌기 때문에, 
///3개의 route를 구분해 놓는다.
///(clientRoutes, commonRoutes, ownerRoutes, )
///deliveryRoutes는 추후 만들예정.

const clientRoutes = [
  { path: '/', element: <Restaurants /> },
  { path: '/search', element: <Search /> },
  { path: '/category/:slug', element: <Category /> },
  { path: '/restaurants/:id', element: <RestaurantDetail /> },
]
///client로 login했을 시, 이동 될 주소 및 component
///component는 element로 받음.
///주소에서 query를 받는 부분, useParams는 :id, :slug등으로
///쓰인다.
///배열로 코딩, 배열안에 object로,
///object는 path와 element로 구성됨.

const commonRoutes = [
  { path: '/confirm', element: <ConfirmEmail /> },
  { path: '/edit-profile', element: <EditProfile /> },
]
///3개의 userRole에 공통적으로 사용되는 page.
///배열로 코딩, 배열안에 object로,
///object는 path와 element로 구성됨.

const ownerRoutes = [
  { path: '/', element: <MyRestaurants /> },
  { path: '/add-restaurant', element: <AddRestaurant /> },
  { path: '/restaurants/:id', element: <MyRestaurant /> },
  { path: '/restaurants/:restaurantId/add-dish', element: <AddDish /> },
]
///owner로 접속했을시, 사용되는 route들..
///배열로 코딩, 배열안에 object로,
///object는 path와 element로 구성됨.

export const LoggedInRouter = () => {
  const { data, loading, error } = useMe()
  ///useMe hook으로 loggedIn된 user의 정보 확인.
  
  console.log(data)
  if (!data || loading || error) {
    return (
      <div className="h-screen flex justify-center items-center">
        <span className="font-medium text-xl tracking-wide">Loading..</span>
      </div>
    )
  }
  ///user의 정보가 없든지, loading중이라든지, error가 있으면,
  ///loading...을 띄움.
  
  return (
    <> ///Router만들때 맨 위에 fragment로 씌워줌,
      {/* <Header /> */}
      <Router>
        <Header />
        <Routes>
          {data.me.role === 'Client' &&
            clientRoutes.map((route, index) => (
              <Route key={index} path={route.path} element={route.element} />
            ))}
            ///role이 Client일떄,
            ///clientRoutes를 맵으로 뿌려준다.
            ///route로 개개별 data를 받고, index를
            ///추가해서 key로 넣는다.
            
          {data.me.role === 'Owner' &&
            ownerRoutes.map((route, index) => (
              <Route key={index} path={route.path} element={route.element} />
            ))}
            ///role이 Owner일때,
            ///ownerRoutes를 맵으로 뿌려준다.
            ///route로 개개별 data를 받고, index를
            ///추가해서 key로 넣는다.
            
          {commonRoutes.map((route, index) => (
            <Route key={index} path={route.path} element={route.element} />
          ))}
          ///role에 상관없이 적용되는 route
          
          <Route path="*" element={<NotFound />}></Route>
          ///없는 주소로 찍혔을때, 보여지는 page.
          
        </Routes>
      </Router>
    </>
  )
}
profile
코딩하는초딩쌤

1개의 댓글

comment-user-thumbnail
2024년 2월 5일

저를 믿으세요. 당신은 다른 사람들에게 build now gg 영감을 주기 위해 단지 몇 단어만을 사용하는 놀라운 재능을 갖고 있기 때문에 당신은 정말 대단합니다.

답글 달기