리액트 강의를 완강하고, 지금까지 배운 내용을 토대로 연습삼아 이것 저것 만들어보던 중에, react router
사용법이 계속 헷갈려서 기록하게 되었다.
원래 기존에 강의에서 배운 방법과 react dom 공식 사이트에서 알려주는 방법이 달라서 그 2가지 모두 작성해보기로 하였다.
https://reactrouter.com/ko/main/start/tutorial#setup
npm install react-router-dom
react 프로젝트 경로의 위치에서 설치 시작하기.
import { BrowserRouter } from "react-router-dom";
ReactDOM.createRoot(document.getElementById("root")).render(
<BrowserRouter>
<App />
</BrowserRouter>
);
import CreatePage from "./pages/CreatePage";
import EditPage from "./pages/EditPage";
import HomePage from "./pages/HomePage";
import ListPage from "./pages/ListPage";
import ShowPage from "./pages/ShowPage";
const routes = [
{
path: "/",
component: HomePage,
},
{
path: "blogs",
component: ListPage,
},
{
path: "/blogs/:id",
component: ShowPage,
},
{
path: "/blogs/create",
component: CreatePage,
},
{
path: "/blogs/edit",
component: EditPage,
},
];
export default routes;
import { Routes, Route } from "react-router-dom";
import routes from "./routes.js";
function App() {
return (
<>
<Routes>
{routes.map((route) => {
return (
<Route
path={route.path}
element={<route.component />}
key={route.path}
></Route>
);
})}
</Routes>
</>
);
}
export default App;
import List from "./pages/List";
import Edit from "./pages/Edit";
import Write from "./pages/Write";
const routes = [
{ path: "/", element: <List /> },
{ path: "/edit", element: <Edit /> },
{ path: "/write", element: <Write /> },
];
export default routes;
import "./App.css";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import routes from "./routes";
function App() {
const router = createBrowserRouter(routes);
return <RouterProvider router={router} />;
}
export default App;
children
옵션을 사용하면 된다.errorElement
옵션을 사용하여 설정하였다.import Layout from "./Layout";
import ErrorPage from "./pages/ErrorPage";
import ListPage from "./pages/ListPage";
import EditPage from "./pages/EditPage";
import WritePage from "./pages/WritePage";
import ViewPage from "./pages/ViewPage";
const routes = [
{
path: "/",
element: <Layout />,
errorElement: <ErrorPage />,
children: [
{ path: "/", element: <ListPage /> },
{ path: "edit", element: <EditPage /> },
{ path: "write", element: <WritePage /> },
{ path: "view/:id", element: <ViewPage /> },
],
},
];
export default routes;
Outlet
을 사용한다.import { Outlet } from "react-router-dom";
const Layout = () => {
return (
<div id="wrap">
<header id="header">header</header>
<Outlet /> // Outlet 사용
<footer id="footer">footer</footer>
</div>
);
};
export default Layout;