๐น ๋ฌธ์ : ๊ฐ๋ณ ํ์ด์ง๋ง๋ค ์ธ์ฆ์ ์ ์ฉํ๋ฉด?
React ์ ํ๋ฆฌ์ผ์ด์ ์์ ๋ก๊ทธ์ธ ํ ํน์ ํ์ด์ง์๋ง ์ ๊ทผํ ์ ์๋๋ก ๋ณดํธํ๋ ๋ฐฉ๋ฒ์ ์ฌ๋ฌ ๊ฐ์ง๊ฐ ์์ต๋๋ค. ํ์ง๋ง ์๋ชป๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ๋ฉด ๋ถํ์ํ ์ฐ์ฐ์ด ๋ฐ์ํ๊ณ , ์ฝ๋์ ์ ์ง๋ณด์์ฑ์ด ๋จ์ด์ง ์ ์์ต๋๋ค.
์ผ๋ฐ์ ์ผ๋ก ์ธ์ฆ์ ์ ์ฉํ๋ ๋ฐฉ๋ฒ ์ค ํ๋๋ ๊ฐ ํ์ด์ง๋ง๋ค ๊ฐ๋ณ์ ์ผ๋ก ์ธ์ฆ ๋ก์ง์ ๊ฐ์ธ๋ ๊ฒ์ ๋๋ค.
โ ๊ฐ๋ณ ํ์ด์ง๋ง๋ค ์ธ์ฆ์ ์ ์ฉํ๋ ๋ฐฉ์
<Route path="/main" element={<AuthenticatedComponent><MainPage /></AuthenticatedComponent>} />
<Route path="/profile" element={<AuthenticatedComponent><ProfilePage /></AuthenticatedComponent>} />
<Route path="/income" element={<AuthenticatedComponent><IncomePage /></AuthenticatedComponent>} />
โก ๋ฌธ์ ์ :
- ๊ฐ ํ์ด์ง๋ง๋ค AuthenticatedComponent๊ฐ ์คํ๋จ → ๋ถํ์ํ ์ฐ์ฐ ์ฆ๊ฐ โ
- ๋ชจ๋ ํ์ด์ง์์ ์ธ์ฆ ๋ก์ง์ด ์ค๋ณต๋จ → ์ ์ง๋ณด์ ์ด๋ ค์ โ
- ๊ณตํต UI(Navbar, Sidebar)๋ ๋ถํ์ํ๊ฒ ๋ฆฌ๋ ๋๋ง๋ ๊ฐ๋ฅ์ฑ โ
๐น ํด๊ฒฐ์ฑ : Layout์ ๊ฐ์ธ ์ธ์ฆ์ ์ต์ ํํ๊ธฐ
๋์ , Layout ์ปดํฌ๋ํธ๋ฅผ AuthenticatedComponent๋ก ํ ๋ฒ๋ง ๊ฐ์ธ์ฃผ๋ฉด ์ธ์ฆ์ด ํ์ํ ๋ชจ๋ ํ์ด์ง์์ ์ธ์ฆ ๊ฒ์ฌ๋ฅผ ํ ๋ฒ๋ง ์ํํ ์ ์์ต๋๋ค.
โ ๊ณตํต ๋ ์ด์์์ ํ์ฉํ ์ต์ ํ๋ ๋ฐฉ์
<Route
element={
<AuthenticatedComponent>
<Layout />
</AuthenticatedComponent>
}
>
<Route path="/main" element={<MainPage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/income" element={<IncomePage />} />
</Route>
โก ์ฅ์ :
- AuthenticatedComponent๊ฐ ํ ๋ฒ๋ง ์คํ๋จ → ๋ถํ์ํ ์ฐ์ฐ ๊ฐ์ โ
- Layout ๋ด๋ถ์ ๋ชจ๋ ํ์ด์ง๊ฐ ์๋ ๋ณดํธ๋จ → ์ค๋ณต ์ฝ๋ ์ ๊ฑฐ โ
- ๊ณตํต UI(Navbar, Sidebar)๊ฐ ์ ์ง๋๋ฉด์ ๋ด๋ถ ํ์ด์ง๋ง ๋ณ๊ฒฝ๋จ → ๋ ๋๋ง ์ต์ ํ โ
๐น AuthenticatedComponent ๊ตฌํ ์์
import { useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { GoalContext } from '../context/GoalContext';
const AuthenticatedComponent = ({ children }) => {
const { goalAmount, loading } = useContext(GoalContext);
const navigate = useNavigate();
useEffect(() => {
if (loading) return;
const accessToken = localStorage.getItem('accessToken');
if (!accessToken) {
alert('๋ก๊ทธ์ธ์ด ํ์ํ ์๋น์ค์
๋๋ค. ๋ก๊ทธ์ธ ํ์ด์ง๋ก ์ด๋ํฉ๋๋ค');
navigate('/login');
return;
}
if (!goalAmount) {
alert('๋ชฉํ ๊ธ์ก์ ์ค์ ํด์ฃผ์ธ์. ๋ชฉํ๊ธ์ก ์ค์ ํ์ด์ง๋ก ์ด๋ํฉ๋๋ค');
navigate('/goal-setting');
}
}, [goalAmount, loading, navigate]);
return children;
};
export default AuthenticatedComponent;
๐ฏ ๊ฒฐ๋ก : ๊ณตํต ๋ ์ด์์์ ํ์ฉํ ์ธ์ฆ์ด ๊ฐ์ฅ ํจ์จ์ !
โ
ํ ๋ฒ๋ง ๊ฐ์ธ๋ ๋ด๋ถ ํ์ด์ง ์ ์ฒด ๋ณดํธ ๊ฐ๋ฅ!
โ
๋ถํ์ํ ์ธ์ฆ ์ฐ์ฐ์ ์ค์ฌ ์ฑ๋ฅ ๊ฐ์ !
โ
์ ์ง๋ณด์ ํธ๋ฆฌ & ์ฝ๋ ์ค๋ณต ์ต์ํ!
React ํ๋ก์ ํธ์์ ๊ณตํต ๋ ์ด์์(Layout)์ ํ์ฉํ ์ธ์ฆ ๋ฐฉ์์ด ๊ฐ์ฅ ์ต์ ํ๋ ๊ตฌ์กฐ์ด๋ฏ๋ก, ์์ผ๋ก ์ธ์ฆ์ด ํ์ํ ๊ฒฝ์ฐ ์ด ๋ฐฉ์์ ํด์. ๋์ ๊ฑด ์๋ค.