Notice
Recent Posts
Recent Comments
Link
ยซ   2024/11   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[React] React Route์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์ž ๋ณธ๋ฌธ

๐Ÿง‘‍๐Ÿ’ป Web/React

[React] React Route์— ๋Œ€ํ•ด ์•Œ์•„๋ณด์ž

Lennon 2022. 5. 19. 17:41
728x90
๋ฐ˜์‘ํ˜•

๋ผ์šฐํŒ…์ด๋ž€?

= ๋„คํŠธ์›Œํฌ ์ƒ์—์„œ url์„ ์ด์šฉํ–ˆ์„ ๋•Œ ์–ด๋–ค ๊ฒฝ๋กœ๋ฅผ ์ด์šฉํ•ด์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์•„์˜ฌ ๊ฑด์ง€ ๊ฒฐ์ •ํ•ด์ฃผ๋Š” ๊ธธ์„ ๊ฒฐ์ •ํ•ด์ฃผ๋Š” ๊ฒƒ

= ์‚ฌ์šฉ์ž๊ฐ€ url์„ ์š”์ฒญํ–ˆ์„ ๋•Œ ์–ด๋–ค ํŠน์ •ํ•œ ํŽ˜์ด์ง€๋กœ ์—ฐ๊ฒฐํ•  ๊ฑด์ง€ ๊ฒฐ์ •ํ•˜๋Š” ๋งค์ปค๋‹ˆ์ฆ˜

= ์‚ฌ์šฉ์ž๊ฐ€ url์„ ์คฌ์„ ๋•Œ ์–ด๋–ค ํŽ˜์ด์ง€๋กœ ์—ฐ๊ฒฐํ•œ๊ฑด์ง€!

 

 

SPA์˜ ๋ฌธ์ œ์ 

์‚ฌ์šฉ์ž๊ฐ€ ๋ถ๋งˆํฌํ•  ์ˆ˜ ์—†๋‹ค. ๋ธŒ๋ผ์šฐ์ €์ƒ์—์„œ ๋’ค๋กœ๊ฐ€๊ธฐ, ์•ž์œผ๋กœ๊ฐ€๊ธฐ์™€ ๊ฐ™์€ ๋„ค๋น„๊ฒŒ์ด์…˜์ด ์ถ”๊ฐ€๊ฐ€ ๋˜์ง€ ์•Š์Œ

 

⇒ ํ•ด๋‹น ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด React Router ๋“ฑ์žฅ

 

React Router?

์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ฃผ์†Œ๋ฅผ ๊ฐ์ง€ํ•˜๋Š” ์—ญํ• ์„ ํ•œ๋‹ค.

import { BrowerRouter, Link, Router, Routes } from 'react-router-dom'

<BrowerRouter> ํƒœ๊ทธ๋กœ ๊ฐ์‹ธ์ค€๋‹ค.

<BrowerRouter>
	
</BrowerRouter>

<Routes> ํƒœ๊ทธ๋กœ path๋งˆ๋‹ค ๋ฌด์Šจ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด์—ฌ์ค„๊ฑด์ง€ ์ž‘์„ฑํ•œ๋‹ค.

<BrowerRouter>
	<Routes>
		<Route path='/' exact element={<Home />}>
		<Route path='/home' exact element={<Home />}>
		<Route path='/profile' exact element={<Profile />}>
	</Routes>
</BrowerRouter>

<Link> ํƒœ๊ทธ๋ฅผ ํ†ตํ•ด ํด๋ฆญ ์‹œ ์ž๋™์œผ๋กœ url์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.

<BrowerRouter>
	<nav>
		<Link to='/'>Home</Link>
		<Link to='/Profile'>Profile</Link>
	</nav>
	<Routes>
		<Route path='/' exact element={<Home />}>
		<Route path='/home' exact element={<Home />}>
		<Route path='/profile' exact element={<Profile />}>
	</Routes>
</BrowerRouter>

Route ์‚ฌ์šฉ ์‹œ path๋ฅผ ์—ฌ๋Ÿฌ ๊ฐœ ์ง€์ •ํ–ˆ์„ ๊ฒฝ์šฐ exact๋ฅผ ์ง€์ •ํ•ด์ฃผ์ž.

v6๋ถ€ํ„ฐ Route ์‚ฌ์šฉ๋ฒ•์ด ์•„๋ž˜ ์ฝ”๋“œ์™€ ๊ฐ™์ด element๋ฅผ ์ง€์ •ํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๋ฐ”๋€Œ์—ˆ๋‹ค.

<Route path='/' exact element={<Home />}>
<Route path='/home' exact element={<Home />}>
<Route path='/profile' exact element={<Profile />}>

 

๋‹ค๋ฅธ ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ•˜๋Š” Hook

v6๋ฒ„์ „ ๋ถ€ํ„ฐ useHistory() ⇒ useNavigate()๋กœ ๋ณ€๊ฒฝ!

const history = useHistory();

history.push('/maker');  // v5

///////////////

const navigate = useNavigate();

navigate('/maker'); // v6

navigate(
	'/maker',
	{ state: {id: ~~~} }); // ํŽ˜์ด์ง€ ์ด๋™ํ•  ๋•Œ ์ธ์ž ์ „๋‹ฌ ๋‹น์—ฐํžˆ ๊ฐ€๋Šฅ

 

728x90
๋ฐ˜์‘ํ˜•
Comments