[React] React Router

์•ค์จฉยท2021๋…„ 12์›” 14์ผ
0

React

๋ชฉ๋ก ๋ณด๊ธฐ
11/11
post-thumbnail

๐Ÿ“• React Router

๋ฆฌ์•กํŠธ ๋ผ์šฐํ„ฐ๋ฅผ ํ•˜๊ธฐ ์ „์— SPA๋ฅผ ์•Œ์•„๋ณผ ํ•„์š”๊ฐ€ ์žˆ๋‹ค.
์šฐ์„  SPA๋ž€ Single Page Application์˜ ์•ฝ์ž์ด๋‹ค. ํŽ˜์ด์ง€๊ฐ€ 1๊ฐœ์ธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์ด๋ผ๋Š” ์ด์•ผ๊ธฐ๋‹ค.
์™œ ์š”์ฆ˜ SPA๊ฐ€ ์ฃผ๋ชฉ์„ ๋ฐ›๋Š๋ƒ๋Š” ๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ๊ฒŒ์‹œ๋ฌผ React๋Š” ๋ฌด์—‡์ธ๊ฐ€?๋ฅผ ์ฐธ๊ณ ํ•˜๋ฉด ๋  ๊ฒƒ์ด๋‹ค. ๊ทธ๋Ÿฐ๋ฐ React์—๋Š” ๊ณต์‹ Router ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค.
๊ทธ๋ž˜์„œ ์šฐ๋ฆฌ๋Š” react-router๋ผ๋Š” ์„œ๋“œํŒŒํ‹ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ ๋ผ์šฐํ„ฐ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•  ๊ฒƒ ์ด๋‹ค.

๐Ÿคž๐Ÿป ํ”„๋กœ์ ํŠธ๋ฅผ ์ค€๋น„ํ•ด๋ณด์ž.

ํ„ฐ๋ฏธ๋„ ๋ช…๋ น์œผ๋กœ ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ

npx create-react-app router-exercise

ํ”„๋กœ์ ํŠธ๋ฅผ ๋งŒ๋“  ํŒŒ์ผ ๋””๋ ‰ํ† ๋ฆฌ๋กœ ์ด๋™ํ•ด react-router-dom ์„ค์น˜

cd router-exercise
// npm ์œผ๋กœ ์„ค์น˜ํ•˜๊ธฐ
npm install react-router-dom@6
// yarn ์œผ๋กœ ์„ค์น˜ํ•˜๊ธฐ
yarn add react-router-dom@6

โœŒ๐Ÿป ํ”„๋กœ์ ํŠธ์— ๋ผ์šฐํ„ฐ ์ ์šฉ

src/index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

src/App.js

import React from "react";
import { Routes, Route, Link } from "react-router-dom";
export default function App () {
  return (
    <div className="App">
      <h1>Welcome to React Router!</h1>
      <Routes>
        <Route path="/" element={<Home />} />
  		<Route path="/about" element={<About />} />
      </Routes>
    </div>
  );
}
--------
function Home () {
  return (
    <>
      <main>
        <h2>Welcome to the homepage!</h2>
    	<p>You can do this, I believe in you.</p>
      </main>
      <nav>
    	<Link to="/about">About</Link>
      </nav>
    </>
  );
}
--------
function About () {
  return (
    <>
      <main>
        <h2>Who are we?</h2>
    	<p>That feels like an existential question, don't you think?</p>
      </main>
      <nav>
    	<Link to="/">Home</Link>
      </nav>
    </>
  );
}

profile
Front-End Developer

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