본문 바로가기
frontend (React) 개발

(React) Routing

by 꼰대코더 2024. 1. 5.

페이지 이동

 

필요한 패키지 인스톨

npm install react-router-dom@6

 

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
 <React.StrictMode>
    <BrowserRouter>
       <App />
    </BrowserRouter>
 </React.StrictMode>
);

 

App.js

path를 정의하고 Component(element)를 연결시킨다.

import { Routes, Route } from 'react-router-dom';
import Home from './Pages/Home';
import About from './Pages/About';
import Products from './Pages/Products';

const App = () => {
 return (
    <>
       <NavBar />
       <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/products" element={<Products />} />
          <Route path="/about" element={<About />} />
       </Routes>
    </>
 );
};

export default App;

 

NavBar.jsx

페이지 상단의 Navigation Bar 를 설정.

App.js 에서 정의한 path 를 이용하여 클릭하면 해당 Component  로 이동.

<Link /> 도 사용할 수 있으나  <NavLink />가 css 의 class 를 이용한 active link 기능을 구현하기 쉬움.

import { NavLink } from 'react-router-dom';

const NavBar = () => {
 return (
    <nav>
       <ul>
          <li>
             <NavLink to="/">Home</NavLink>
          </li>
          <li>
             <NavLink to="/about">About</NavLink>
          </li>
          <li>
             <NavLink to="/products">Products</NavLink>
          </li>
       </ul>
    </nav>
 );
};

export default NavBar;

 

 

Page Not Found Error 대응

App.js 

import { Routes, Route } from 'react-router-dom';
import Home from './Pages/Home';
import About from './Pages/About';
import Products from './Pages/Products';

const App = () => {
 return (
    <>
       <NavBar />
       <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/products" element={<Products />} />
          <Route path="/about" element={<About />} />
          <Route path="*" element={<NoMatch />} />
       </Routes>
    </>
 );
};

export default App;

 

프로그램으로 Navigate

  • login / logout
  • signup /signout
  • order success
  • back button

useNavigate()

미리 App.js 에 path="/order" 가 정의 되었다고 가정했을 시

import { useNavigate } from 'react-router-dom';

const Products = () => {
 const navigate = useNavigate();
 return (
    <div className="container">
       <div className="title">
          <h1>Order</h1>
       </div>
       <button className="btn" onClick={() => navigate('/order')}>
          Place Order
       </button>
    </div>
 );
};

export default Products;

 

직전 페이지 이동

<button className="btn" onClick={() => navigate(-1)}>
 Go Back
</button>

 

 

Dynamic Routing

App.js 에 item 파라미터에 의한 상세정보 표시의 ProductDetails 컴포넌트 Route path 를 정의

       <Routes>
          // ...
          <Route path="/products/:item" element={<ProductDetails />} />
       </Routes>

 

ProductDetails.jsx

import { useParams } from 'react-router-dom';

const ProductDetails = () => {
 const { item } = useParams();
 return (
    <div className="container">
       <h1>Products Details Page - {item}</h1>
    </div>
 );
};

export default ProductDetails;

 

Product.jsx

import { Link } from 'react-router-dom';

const Products = () => {
   ...

 return (
      ...
       <div>
          {products.map((product) => (
             <div key={product.id}>
                <img src={product.image.url} alt="" />
                <div>
                   <div>
                      <h2>{product.name}</h2>
                      <span className="info">{product.info}</span>
                   </div>
                   <Link to={`/products/${product.item}`}>
                      <div>View Details</div>
                   </Link>
                </div>
             </div>
          ))}
       </div>
    </div>
 );
};

export default Products;

 

Lazy Loading

App.js

import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

import NavBar from './Components/NavBar';
const Home = lazy(() => import('./Pages/Home'));
const About = lazy(() => import('./Pages/About'));
const Products = lazy(() => import('./Pages/Products'));
const ProductDetails = lazy(() => import('./Pages/ProductDetails'));
const NoMatch = lazy(() => import('./Components/NoMatch'));

const App = () => {
 return (
    <>
       <NavBar />
       <Suspense fallback={<div className="container">Loading...</div>}>
          <Routes>
             <Route path="/" element={<Home />} />
             <Route path="/about" element={<About />} />
             <Route path="/products" element={<Products />} />
             <Route path="/products/:item" element={<ProductDetails />} />
             <Route path="*" element={<NoMatch />} />
          </Routes>
       </Suspense>
    </>
 );
};

export default App;