[리액트]react-router v6에서의 라우팅 방법

JH Bang·2023년 4월 9일
0

프론트엔드

목록 보기
2/6

Browser Router 방식

index.tsx

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>
);

App.tsx

<Router />를 삽입한다.

import Router from "./Router";

function App() {
  return (
    <div>
      <Router />
    </div>
  );
}

export default App;

Router.tsx

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;

screens/Home.tsx

function Home() {
	return <h1>Home</h1>
}
export default Home;

screens/Login.tsx

function Login() {
	return <h1>Login</h1>
}
export default Login;

screens/components/Header.tsx

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;

createBrowserRouter 방식

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>
);

Router.tsx

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;

App.tsx

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;

헤더 링크를 버튼으로 변경

Header.tsx

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;
profile
의지와 행동

0개의 댓글