| react-router-dom
๋ฆฌ์กํธ์ ๋ผ์ฐํ ์ ์ํ ํต์ฌ ๋ผ์ด๋ธ๋ฌ๋ฆฌ.
(์๋๋ ๋ผ์ฐํ ์ค์ , ํ๋ผ๋ฏธํฐ์ ์ฟผ๋ฆฌ ํ์ฉ, ์๋ธ๋ผ์ฐํธ ๊ตฌ์ฑ, ๊ทธ๋ฆฌ๊ณ history ๊ฐ์ฒด๋ฅผ ๋ค๋ฃจ๋ ๋ฐฉ๋ฒ)
| ์ค์น ๋ฐ ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
1. react-router-dom ์ค์น
yarn add react-router-dom@5
- ํน์ ์ฃผ์์ ์ปดํฌ๋ํธ๋ฅผ ์ฐ๊ฒฐํ ๋ Route ์ปดํฌ๋ํธ๋ฅผ ์ฌ์ฉ
<Route path="์ฃผ์" component={๋ณด์ฌ์ค_์ปดํฌ๋ํธ} />
- ์ฃผ์์ด๋์ Link ์ปดํฌ๋ํธ๋ก ์ฒ๋ฆฌ
import { Route, Link } from 'react-router-dom';
<Link to="์ฃผ์">๋ฌธ์</Link>
| ํ๋ผ๋ฏธํฐ์ ์ฟผ๋ฆฌ
ํ์ด์ง ์ฃผ์ ์ ์ ์ ์ ๋์ ์ธ ๊ฐ์ ์ ๋ฌํด์ผ ํ ๋๋ ํ๋ผ๋ฏธํฐ๋ ์ฟผ๋ฆฌ๋ฅผ ์ฌ์ฉํจ.
- ํ๋ผ๋ฏธํฐ: ํน์ ID๋ ์ด๋ฆ ์กฐํ ์ ์ฌ์ฉํจ.
์: /profile/apple - ์ฟผ๋ฆฌ: ๊ฒ์ ํค์๋๋ ์ต์
์ ๋ฌ ์ ์ฌ์ฉํจ.
์: /profile?name=apple
- ํ๋ผ๋ฏธํฐ๋ ๋ผ์ฐํธ ๊ฒฝ๋ก์์ :ํ๋ผ๋ฏธํฐ๋ช ์ผ๋ก ์ค์ ๊ฐ๋ฅํจ.
<Route path="/profile/:username" component={Profile} />
- ์ฟผ๋ฆฌ๋ ๋ฌธ์์ด๋ก ์ฒ๋ฆฌํ ์๋ ์์ง๋ง, ๊ฐ์ฒด๋ก ๋ณํํ๋ ค๋ฉด qs ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฉด ํธํจ.
yarn add qs
| ์๋ธ๋ผ์ฐํธ
์๋ธ๋ผ์ฐํธ๋ ๋ผ์ฐํธ ๋ด๋ถ์ ๋ ๋ค๋ฅธ ๋ผ์ฐํธ๋ฅผ ๋ง๋๋ ๊ฒ์ ์๋ฏธ
<Route path="/main" component={Main}>
<Route path="/main/sub" component={SubComponent} />
</Route>
| history ๊ฐ์ฒด
history ๊ฐ์ฒด๋ ์ปดํฌ๋ํธ ๋ด์์ ๋ผ์ฐํฐ์ ์ง์ ์ ๊ทผ ๊ฐ๋ฅํ๊ฒ ํด์ค.
- ๋ค๋ก๊ฐ๊ธฐ
- ํน์ ๊ฒฝ๋ก ์ด๋
- ํ์ด์ง ์ดํ ๋ฐฉ์ง
ํน์ ์กฐ๊ฑด์์ ๊ฒฝ๋ก๋ฅผ ์ด๋ํ๋ ค๋ฉด ์๋์ฒ๋ผ ์ฌ์ฉ
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
const handleNavigate = () => {
history.push('/new-route');
};
return <button onClick={handleNavigate}>Go</button>;
};