사고쳤어요
[React / ts] Book Store 만들기 - ⑤ 라우터 만들기 본문
https://www.npmjs.com/package/react-router-dom
react-router-dom
Declarative routing for React web applications. Latest version: 7.5.1, last published: 4 days ago. Start using react-router-dom in your project by running `npm i react-router-dom`. There are 23676 other projects in the npm registry using react-router-dom.
www.npmjs.com
https://www.npmjs.com/package/@types/react-router-dom
@types/react-router-dom
TypeScript definitions for react-router-dom. Latest version: 5.3.3, last published: 3 years ago. Start using @types/react-router-dom in your project by running `npm i @types/react-router-dom`. There are 1776 other projects in the npm registry using @types/
www.npmjs.com
다음 명령어롤 통해 react-router-dom과 @types/react-router-dom을 설치해준다.
npm install react-router-dom @types/react-router-dom --save
다음과 같이 router를 정의해준다.
const router = createBrowserRouter([
{
path: "/",
element: (
<Layout>
<Home />
</Layout>
),
errorElement: <Error />,
},
{
path: "/books",
element: <div>도서 목록</div>,
},
]);
createBrowserRouter를 통해 path와 elment를 정의해줄 수 있다.
이제 "/"로 접속하면 <Home> 컴포넌트가 출력될 것이고, "/books"로 접속하면 <div>도서 목록</div> 컴포넌트가 출력될 것이다.
그리고 루트 경로인 "/"에 errorElement가 <Error />로 정의되어 있다.
이는 모든 페이지에 대하여 ("/"의 하위 페이지) 오류가 발생하는 경우 <Error /> 를 출력하도록 하는 것이다.
만약 다른 경로의 하위 페이지에 대하여 오류가 발생하는 경우를 조절하고 싶다면 해당 errorElement를 설정해주면 될 것이다.
function App() {
return (
<BookStoreThemeProvider>
<ThemeSwitcher />
<RouterProvider router={router} />
</BookStoreThemeProvider>
);
}
Router는 위와 같이 App()에서 <RouterProvider router={router} />을 통해 설정해주어야 정상 작동한다.
// Error.tsx
import { useRouteError } from "react-router-dom";
interface RouteError {
statusText?: string;
message?: string;
}
const Error = () => {
const error = useRouteError() as RouteError;
return (
<div>
<h1>오류가 발생하였습니다</h1>
<p>다음과 같은 오류가 발생하였습니다</p>
<p>{error.statusText || error.message}</p>
</div>
);
};
export default Error;
마지막으로 errorElement에 사용했던 Error.tsx이다.
useRouteError()를 사용하여 error의 statusText와 message를 보여주도록 하였다.
'웹 풀스택' 카테고리의 다른 글
[React / ts] Book Store 만들기 - ⑦ Zustand를 활용한 로그인 구현 (0) | 2025.04.23 |
---|---|
[React / ts] Book Store 만들기 - ⑥ Axios 사용과 웹서버 연결 (1) | 2025.04.21 |
[React / ts] Book Store 만들기 - ④ 컴포넌트 제작과 테스트파일 만들기 (0) | 2025.04.20 |
[React / ts] Book Store 만들기 - ③ ThemeSwitcher 만들기 (0) | 2025.04.19 |
[React / ts] Book Store 만들기 - ② 레이아웃 구성, 글로벌 스타일 적용 (0) | 2025.04.18 |