jwj3400
[Front] React Router 본문
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>
...
'코딩 > web' 카테고리의 다른 글
[backend] XSS(Cross Site Scripting) & CSRF (Cross-Site Request Forgery) (0) | 2023.10.06 |
---|---|
[backend] CORS (Cross-Origin Resource Shari) (0) | 2023.08.25 |
[Front] CSS Margin, borader, padding 차이 (0) | 2023.08.22 |
[Front] CSS 중앙 잡기 (0) | 2023.08.16 |
[Front] CSS 포지션 (0) | 2023.08.14 |