この記事の概要
react-router-domの使い方について記す
react-router-domのバージョン: v6
react-router-domのインストール
// react-router-domのインストール
$ npm install react-router-dom
react-router-domの使い方
App.js
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import Layout from './pages/Layout';
import NotFound from './pages/NotFound';
import Page1 from './pages/Page1';
import Page2 from './pages/Page2';
import Page3 from './pages/Page3';
import Posts from './pages/Posts';
import Post from './pages/Post';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Layout />}>
<Route index element={<Home />} />
<Route path='page1' element={<Page1 />} />
<Route path='page2' element={<Page2 />} />
<Route path='page3' element={<Page3 />} />
<Route path='posts' element={<Posts />} />
<Route path='posts/:postId' element={<Post />} />
<Route path='*' element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
)
}
export default App;
Home.js
/* Home.js */
import { Link } from "react-router-dom";
const Home = () => {
return (
<>
<h1>Home</h1>
<ul>
<li><Link to='page1'>Page1</Link></li>
<li><Link to='page2'>Page2</Link></li>
<li><Link to='page3'>Page3</Link></li>
<li><Link to='posts'>Posts</Link></li>
</ul>
</>
);
};
export default Home;
Layout.js
/* Layout.js */
import { Link, Outlet } from "react-router-dom";
const Layout = () => {
return (
<>
<ul>
<li><Link to='page1'>Layout Page1</Link></li>
<li><Link to='page2'>Layout Page2</Link></li>
<li><Link to='page3'>Layout Page3</Link></li>
<li><Link to='posts'>Layout Posts</Link></li>
</ul>
<Outlet />
</>
);
};
export default Layout;
NotFound.js
/* NotFound.js */
import { Link } from "react-router-dom";
const NotFound = () => {
return (
<>
<h1>NotFound404</h1>
<h2>お探しのページは見つかりませんでした</h2>
<Link to='/'>Homeへ戻る</Link>
</>
);
};
export default NotFound;
Page1.js
/* Page1.js */
import { Link } from "react-router-dom";
const Page1 = () => {
return (
<>
<h1>Page1</h1>
<Link to='/'>Homeへ戻る</Link>
</>
);
};
export default Page1;
Posts.js
/* Posts.js */
import { Link } from "react-router-dom";
const Posts = () => {
return (
<>
<h1>Posts</h1>
<ul>
<li><Link to='1'>Post1</Link></li>
<li><Link to='2'>Post2</Link></li>
<li><Link to='3'>Post3</Link></li>
</ul>
<p><Link to='/'>Homeに戻る</Link></p>
</>
);
};
export default Posts;
Post.js
/* Post.js */
import { Link, useParams } from "react-router-dom";
const Post = () => {
const { postId } = useParams();
return (
<>
<h1>Post</h1>
<p>ID: {postId}</p>
<ul>
<li><Link to='/posts'>一覧に戻る</Link></li>
</ul>
</>
);
};
export default Post;