import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<Router />를 삽입한다.
import Router from "./Router";
function App() {
return (
<div>
<Router />
</div>
);
}
export default App;
path를 통해 라우트를 설정한다. element로 각각 Home과 Login 모듈을 가져온다. Header 모듈은 중복을 피하기 위함이다.
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Header from "./screens/components/Header";
import Home from "./screens/Home";
import Login from "./screens/Login";
function Router() {
return <BrowserRouter>
<Header></Header>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
}
export default Router;
function Home() {
return <h1>Home</h1>
}
export default Home;
function Login() {
return <h1>Login</h1>
}
export default Login;
import { Link } from "react-router-dom"
function Header() {
return (
<h1>
<ul>
<li>
<Link to={"/"}>Home</Link>
</li>
<li>
<Link to={"/login"}>Login</Link>
</li>
</ul>
</h1>
);
}
export default Header;
index.tsx에 <App /> 대신 RouterProvider를 삽입. router를 가져온다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { RouterProvider } from 'react-router-dom';
import router from './Router';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
Routes 컴포넌트를 하나하나 설정하는 대신 createBrowserRouter로 배열 형식으로 삽입.
import { Route, Routes, createBrowserRouter } from "react-router-dom";
import Header from "./screens/components/Header";
import Home from "./screens/Home";
import Login from "./screens/Login";
import App from "./App";
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{
path: "",
element: <Home />,
},
{
path: "login",
element: <Login />,
},
],
},
]);
export default router;
Router 컴포넌트 대신 Header 컴포넌트와 Outlet 컴포넌트를 삽입. Outlet컴포넌트는 하위 라우트가 설정돼 있으면 해당 컴포넌트를 갖고와 주는 역할.
import { Outlet } from "react-router-dom";
import Header from "./screens/components/Header";
function App() {
return (
<div>
<Header />
<Outlet />
</div>
);
}
export default App;
useNavigate 훅을 사용.
import { Link, useNavigate } from "react-router-dom"
function Header() {
const nav = useNavigate();
const onLoginClick = () => {
nav("/login");
};
return (
<h1>
<ul>
<li>
<Link to={"/"}>Home</Link>
</li>
<li>
<button onClick={onLoginClick}>Login</button>
</li>
</ul>
</h1>
);
}
export default Header;
errorElement를 추가해준다.
const router = createBrowserRouter([
{
path: "/",
element: <App />,
children: [
{
path: "",
element: <Home />,
errorElement: <CrashError />,
},
{
path: "login",
element: <Login />,
errorElement: <CrashError />,
},
],
errorElement: <NotFound />,
},
]);
export default router;