💻웹(Web)

[React]React Router

stonesy 2024. 6. 28. 13:46
728x90

React Router

단계

1. react router 설치

npm install react-router-dom

 

2. src/main.jsx 또는 src/main.tsx 파일을 열어 React Router의 BrowserRouter로 애플리케이션을 감싼다.

import React from 'react'
import ReactDOM from 'react-dom/client'
import { Provider } from 'react-redux';
import { store } from './app/store';
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Provider store={store}>
        <BrowserRouter> 
          <App />
        </BrowserRouter>
    </Provider>
  </React.StrictMode>,
)

 

3. router.jsx 작성

import { Routes, Route } from 'react-router-dom';
import Home from './pages/HomePage';
import Nasa from './pages/NasaPage';

const AppRoutes = () => {
  return (
    <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/nasa" element={<Nasa />} />
    </Routes>
  );
};

export default AppRoutes;

 

4. App.jsx에서 router.jsx로 요소들 대체

import Login from "./components/Login";
import AppRoutes from "./routes";
import { Link } from "react-router-dom";

function App() {
  return (
    <>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/nasa">Nasa</Link>
          </li>
        </ul>
      </nav>
      <Login />
      <AppRoutes />
    </>
  )
}

export default App;

 

권한별 라우팅

고차 컴포넌트 (Higher-Order Component, HOC)를 이용하여 권한별 라우팅을 구현하였다. PrivateRoute 컴포넌트를 사용하여 특정 라우트에 접근하려면 인증이 필요하도록 설정했다.

*privateRoute

import { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';

const PrivateRoute = ({ children }) => {
  const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
  const navigate = useNavigate();

  useEffect(() => {
    if (!isAuthenticated) {
      alert('접근 권한이 없습니다. 로그인 해주세요.');
      navigate('/');
    }
  }, [isAuthenticated, navigate]);

  return isAuthenticated ? children : null;
};

PrivateRoute.propTypes = {
  children: PropTypes.node.isRequired,
};

export default PrivateRoute;

728x90