WEB/React
[React] 라우트(Route) 설정하기
스용공주
2025. 4. 19. 13:39
728x90
728x90
import { Routes, Route } from 'react-router-dom'
// /입력 시 Home, /new new, /diary diary 각각의 페이지를 가져오도록 하기 위함
Routes와 Route를 사용하면 원하는 경로로 원하는 컴포넌트를 연결해줄 수 있다.
return (
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/new" element={<New/>}/>
<Route path="/diary" element={<Diary/>}/>
<Route path="*" />
</Routes>
// path는 경로 element는 해당 경로에서 렌더링할 컴포넌트 작성
// Routes는 위에서부터 순서대로 순회
// ex. /new라는 path를 찾았다면 해당 <New> 컴포넌트에 해당하는 페이지를 렌더링
// path가 *일 경우 위의 조건들이 모두 없을 경우 띄우는 페이지 (default)
)
}
import "./App.css";
import { Routes, Route } from "react-router-dom";
import Diary from "./pages/Diary";
import Home from "./pages/Home";
import New from "./pages/New";
import Notfound from "./pages/NotFound";
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/new" element={<New />} />
<Route path="/diary" element={<Diary />} />
<Route path="*" />
</Routes>
);
}
export default App;
주의사항 1) Routes 컴포넌트 안에는 Route 컴포넌트만 들어갈 수 있다.
주의사항 2) Routes 컴포넌트 밖에 작성된 것은 모든 페이지에 렌더링된다.
728x90
728x90