[React] React-router-dom

Jinnyยท2023๋…„ 11์›” 14์ผ
1

React

๋ชฉ๋ก ๋ณด๊ธฐ
8/23

1. React-router-dom

1) react-router-dom ์„ค์น˜ : yarn add react-router-dom;

๐Ÿ“shared ๐Ÿ‘‰ Router.js ์ƒ์„ฑ
๐Ÿ“ pages ๐Ÿ‘‰ Home.jsx, LetterDetail.jsx ์ƒ์„ฑ

2) Router.js์—์„œ ๋ผ์šฐํ„ฐ๋ฅผ ์„ค์ •ํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•œ๋‹ค.

import {BrowserRouter,Route,Routes} from 'react-router-dom';
import Home from '../pages/Home';
import Detail from '../pages/Detail';

const Router = () => {
  return (
    <BrowerRouter>
      <Routes>
    //์ด ์•ˆ์— ๋ผ์šฐํŠธ๋ฅผ ๋„ฃ์Œ. 
       <Route path = "/" element = {<Home />} />
	  <Route path = "/detail" element = {<Detail />} />
       </Routes>
    </BrowerRouter>
    )
}
export default Router;
  • Route ์ปดํฌ๋„ŒํŠธ์—์„œ path ์†์„ฑ์€ ๊ฒฝ๋กœ๋ฅผ, element๋Š” ๋ณด์—ฌ์ค„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ง€์นญํ•œ๋‹ค.

3) App.js๋‚˜ index.js์—์„œ exportํ•œ router๋ฅผ importํ•œ๋‹ค.
(react-rotuer-dom์—์„œ ์ œ๊ณตํ•˜๋Š” Router๊ฐ€ ์•„๋‹˜์„ ์œ ์˜ํ•˜์ž!)

import Router from '../shared/Router';

function App() {
  return (
    <Router/>;
  )
}

โžก๏ธ ์ตœ์ƒ์œ„ ๊ฒฝ๋กœ์—์„œ๋Š” Home ์ปดํฌ๋„ŒํŠธ๋ฅผ, '/detail' ๊ฒฝ๋กœ๋กœ ์ด๋™ํ•˜๋ฉด Detail ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค.

1.1 Outlet ํ™œ์šฉ

๋งŒ์•ฝ Navbar์™€ ๊ฐ™์ด ์ƒ์œ„์— ๊ณ ์ •ํ•˜๊ณ  ์›ํ•˜๋Š” ๋ถ€๋ถ„๋งŒ ํ™”๋ฉด์„ ์—…๋ฐ์ดํŠธํ•˜๊ณ  ์‹ถ์„ ๋•Œ Outlet์„ ์ด์šฉํ•œ๋‹ค.

์•„์šธ๋ ›์„ ์ง€์ •ํ•˜๋ฉด ์›ํ•˜๋Š” ์ž์‹ ๋ฃจํŠธ๋“ค์„ ์•„์šธ๋ › ์•ˆ์— ํ‘œ๊ธฐํ•  ์ˆ˜ ์žˆ๋‹ค.

Router.js

import App from 'App';
import Home from 'pages/Home';
import Detail from 'pages/Detail';
import { BrowserRouter, Route, Routes } from 'react-router-dom';

const Router = () => {
    return (
        <BrowserRouter>
            <Routes>
                <Route path='/' element={<App />}>
                    <Route path='' element={<Home />} />
                    <Route path='detail' element={<LetterDetail />} />
                </Route>
            </Routes>
        </BrowserRouter>
    )
}

export default Router;
  • ํ™ˆ ๊ฒฝ๋กœ('/')๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” Route ํƒœ๊ทธ ์•ˆ์— ์ž์‹ ์š”์†Œ๋กœ
    Home ์ปดํฌ๋„ŒํŠธ์™€ Detail ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
  • ์ด๋ฏธ ๋ถ€๋ชจ Route๊ฐ€ '/' ์„ ํฌํ•จํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— detail๋งŒ ์ž…๋ ฅํ•ด๋„ /detail ๊ฒฝ๋กœ๋กœ ์ธ์‹ํ•œ๋‹ค.
import { Outlet } from 'react-router-dom';

function App() {
  return (
    <div className='App'>
      <Banner />
      <Outlet />
    </div>
  );
}

export default App;

โžก๏ธ ์ƒ๋‹จ์— Banner ์ปดํฌ๋„ŒํŠธ๋Š” ์ƒ๋‹จ์— ์œ ์ง€๋˜๋ฉฐ,
Outlet์„ ํ†ตํ•ด ์ค‘์ฒฉ๋œ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ(Home,Detail)์„ ๋ณด์—ฌ์ค„์ˆ˜ ์žˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€