- 리액트 라우터 공식 문서 :
https://reactrouter.com/en/main
Home v6.4.4
I'm on v5 The migration guide will help you migrate incrementally and keep shipping along the way. Or, do it all in one yolo commit! Either way, we've got you covered to start using the new features right away.
reactrouter.com
사용 방법
1. 패키지 다운받기 yarn add / npm i react-router-dom
2. createBrowserRouter({}) 로 함수 내 path, element, errorElement 요소를 통해 경로 및 보여줄 화면 지정
3. 적용해줄 요소에 RouterProvider 태그로 감싸주기
- 사용 예시 코드 :
import{
RouterProvider,
createBrowserRouter,
Routes,
Route
} from 'react-router-dom';
const router = createBrowserRouter([
{
path:'/',
element: <p>Hi</p>
},
{
path:'/videos',
element: <p>trending Videos</p>
}
])
function App() {
return (
<RouterProvider router={router} />
);
}
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import{
RouterProvider,
createBrowserRouter,
} from 'react-router-dom';
import NotFound from './pages/NotFound';
import Videos from './pages/Videos';
import VideoDetail from './pages/VideoDetail';
const router = createBrowserRouter([
{
path:'/',
element: <App />,
errorElement : <NotFound />,
children : [{
index : true,
element : <Videos />
},
{
path : 'videos',
element : <Videos />
},
{
path : 'videos/:keyword',
element : <Videos />
}, {
path: 'videos/watch/:videoId',
element : <VideoDetail />
}]
}
])
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
- 아울렛 공식 문서 :
https://reactrouter.com/en/main/components/outlet
Outlet v6.8.1
Type declarationinterface OutletProps { context?: unknown; } declare function Outlet( props: OutletProps ): React.ReactElement | null; An should be used in parent route elements to render their child route elements. This allows nested UI to show up when ch
reactrouter.com
상위 요소의 children 요소로 넣어줄 위치에 <Outlet/> 추가해주기
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
{/* This element will render either <DashboardMessages> when the URL is
"/messages", <DashboardTasks> at "/tasks", or null if it is "/"
*/}
<Outlet />
</div>
);
}
'Frontend > React' 카테고리의 다른 글
[React] useNavigate(), useLocation() (0) | 2023.02.16 |
---|---|
[React] timeago 라이브러리 (0) | 2023.02.15 |
[React] 클래스 컴포넌트 (Class Component) (0) | 2023.02.07 |
[React] 커스텀 훅 (Custom Hook) (0) | 2023.02.06 |
[React] Context란? (2) | 2023.02.05 |