[React] React Router

fejiguยท2022๋…„ 8์›” 1์ผ
1

React

๋ชฉ๋ก ๋ณด๊ธฐ
4/16


๐Ÿ”Ž React SPA์— ์ด์–ด์„œ React Router์— ๋Œ€ํ•ด์„œ ํ•™์Šตํ•˜๊ณ ์ž ํ•œ๋‹ค.

๋ผ์šฐํŒ…์ด๋ž€ ๋ฌด์—‡์ธ์ง€, ๋ผ์šฐํŒ…์„ ์œ„ํ•ด ์‚ฌ์šฉํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ React Router๋ฅผ ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•˜๋Š”์ง€, React Router ์ฃผ์š” ์ปดํฌ๋„ŒํŠธ๋กœ๋Š” ์–ด๋– ํ•œ ๊ฒƒ๋“ค์ด ์žˆ๊ณ  ๊ฐ๊ฐ์˜ ์—ญํ• ์€ ๋ฌด์—‡์ธ์ง€์— ๋Œ€ํ•ด ์ •๋ฆฌํ•ด๋ณด๊ณ ์ž ํ•œ๋‹ค.


โœ”๏ธ Routing์ด๋ž€

SPA๋Š” ํ™”๋ฉด์— ๋”ฐ๋ผ ์ฃผ์†Œ๋„ ๋‹ฌ๋ผ์ง€๋Š”๋ฐ,
๋‹ค๋ฅธ ์ฃผ์†Œ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ณผ์ •์„ ๊ฒฝ๋กœ์— ๋”ฐ๋ผ ๋ณ€๊ฒฝํ•œ๋‹ค๊ณ  ํ•˜๋ฉฐ, Routing์ด๋ผ๊ณ  ํ•œ๋‹ค.


โœ”๏ธ React Router๋ž€

React SPA์—์„œ๋Š” ๋ผ์šฐํŒ…์„ ์œ„ํ•ด ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๋ฐ,
๊ทธ ์ค‘ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด React Router๋ผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋‹ค.


โœ”๏ธ React Router ์ฃผ์š” ์ปดํฌ๋„ŒํŠธ

1) ๋ผ์šฐํ„ฐ ์—ญํ•  : BrowserRouter(React Router DOM์ด ์‚ฌ์šฉ๋˜๋Š” ๋ถ€๋ถ„์˜ ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ๋กœ ์œ„์น˜)
2) ๊ฒฝ๋กœ ๋งค์นญ ์—ญํ•  : Routes ์™€ Route(Routes ์ปดํฌ๋„ŒํŠธ์˜ ์ž์‹ ์ปดํฌ๋„ŒํŠธ)
3) ๊ฒฝ๋กœ ๋ณ€๊ฒฝ ์—ญํ•  : Link( ํ•ด๋‹น ์ปดํฌ๋„ŒํŠธ๋ฅผ ํด๋ฆญํ•  ๋•Œ, Route์˜ path์™€ ์ผ์น˜ํ•˜๋Š” ํŽ˜์ด์ง€๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ์ปดํฌ๋„ŒํŠธ)


์ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด React Router์—์„œ ๋”ฐ๋กœ ๋ถˆ๋Ÿฌ์™€์•ผ ํ•œ๋‹ค
๋ถˆ๋Ÿฌ์˜ค๋Š” ๋ช…๋ น์–ด๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค

import {BrowserRouter,Routes,Route,Link} from "react-router-dom";

โœ”๏ธ React Router ํ™˜๊ฒฝ ์„ธํŒ…

1. react-router ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜

// ์›ํ•˜๋Š” ํด๋”์— React App ์„ค์น˜
npx create-react-app simpleroute cd simpleroute
// react-router ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜
npm install react-router-dom@^6.3.0

2. App.js๋กœ react-router ์ปดํฌ๋„ŒํŠธ ๊บผ๋‚ด์˜ค๊ธฐ

import React from "react";
import {BrowserRouter,Routes,Route,Link} from "react-router-dom";
export default function App() {
	return (...)}
profile
์‹ ๊ทœ ์„œ๋น„์Šค์˜ ๊ธฐํš๋ถ€ํ„ฐ ๊ฐœ๋ฐœ, ์šด์˜๊นŒ์ง€ ์ „ ๊ณผ์ •์„ ๊ฒฝํ—˜ํ•œ ์ฃผ๋‹ˆ์–ด ๐Ÿ“ฑ

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