Link
태그
to 속성으로 직접 경로를 지정한다. (html a 태그와 유사)
import React from 'react';
import { Link } from 'react-router-dom';
export default function Navbar() {
return (
<nav>
<Link to='/'>Home</Link>
<Link to='/videos'>Videos</Link>
</nav>
);
}
useNavigate
Hook
메소드를 이용하여 코드에서 동적으로 이동한다.
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
export default function Videos() {
const [text, setText] = useState('');
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
setText('');
navigate(`/videos/${text}`);
};
const handleChange = (e) => {
setText(e.target.value);
};
return (
<div>
Videos
<form onSubmit={handleSubmit}>
<input
type='text'
placeholder='video id: '
value={text}
onChange={handleChange}
/>
</form>
</div>
);
}
router 객체 사용
const router = createBrowserRouter([
{
path: '/',
element: <Root />,
errorElement: <NotFound />,
children: [
{ index: true, element: <Home /> },
{ path: '/videos', element: <Videos /> },
{ path: '/videos/:videoId', element: <VideoDetail /> },
],
},
]);
const router = createBrowserRouter(
createRoutesFromElements(
<Route element={<Root />}>
<Route index={true} element={<Home />} />
<Route path='/videos' element={<Videos />}>
<Route path='/videos' element={<Videos />} />
</Route>
<Route path='/videos/:videoId' element={<VideoDetail />} />
</Route>
)
);
Link 또는 useNavigate로 navigating 한다.
이동한 페이지에서 useParams
Hook을 이용해 변수를 받아온다.
import React from 'react';
import { useParams } from 'react-router-dom';
export default function VideoDetail() {
const { videoId } = useParams();
return <div>Video Detail: {videoId}</div>;
}