Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

jwj3400

[Front] React Router 본문

코딩/web

[Front] React Router

jwj3400 2023. 8. 23. 17:47

React-router-dom (v6 기준)

  • BrowserRouter: history API를 이용해 UI를 업데이트, SPA(single page application)은 화변의 header나 footer, sidebar등 다시 로드해도 변함없는 부분이 있고 BrowserRouter는 변경되는 부분만 부분적으 렌더링함
  • Routes: Route로 생성된 자식 컴포넌트 중에 path와 url이 대응되는 컴포넌트 렌더링(element 요소) 이때 url이 중복되는 경우 먼저 마주치는 컴포넌트를 렌더링 (순서가 중요) 
    ex) 아래코드에서 /secondPage에 접근해도 FirstPage로 넘어가짐
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';

const Router = () => {

return (
		<>
		<BrowserRouter>
		<Routes>
			<Route path="/*" element = {<FirstPage />} />
    		<Route path="/secondPage" element = {<SecondPage />} />
		</Routes>
		</BrowserRouter>
		</>
	);
};

export default Router;

 

PrivateRoute

  • PrivateRoute는 권한에 따라 페이지 접근을 제한.
    예를 들어 만약 로그인하지 않은 사용자가 인증이 필요한 루트로 접근하고자 한다면 로그인 페이지로 Redirection
  • PrivateRoute 컴포넌트는 path와 element 두개의 props를 받음
    path: 이동하고 싶은 페이지 경로
    element: 해당 경로에서 렌더링 할 react 요소
    (useContext를 사용해 AuthContext로부터 현재 인증 상태를 가져와서 AuthState.isLoggedIn을 통해 사용자가 로그인 되어있는지 확인)
  • v6에서는 route를 nested로 사용한 뒤 <outlet />을 사용해서 로그인이 되면 자식 컴포넌트(원하는 페이지)를 렌더링 하고 그렇지 않으면 원하는페이지로 이동시킴 ( outlet은 하위 컴포넌트의 구역 지 )

//location: src/utils
import React, { useContext } from 'react';
import { Outlet, Navigate } from 'react-router-dom';
import AuthContext from '../context/AuthContext';

function PrivateRoutes() {
  const authState = useContext(AuthContext);
  
  if (authState.isLoggedIn) {
    return <Outlet />;
  } else {
    return <Navigate to="/login" />;
  }
}

export default PrivateRoutes;

 

// location: app.js
...
<Routes>
        <Route element={<PrivateRoutes/>}>
          <Route path='' element={<Home />}/>
          <Route path='content' element={<Content />}/>
          <Route path='strategy' element={<Strategy />}/>
        </Route>
</Routes>
...