0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

React: react-router-dom (v6) の使い方

Posted at

こちらのページを参考にしました。
React Router v6 はじめでもわかるルーティングの設定方法の基礎

次のようーなページを作成します。

ホーム
router_aa.png

紹介
router_bb.png

連絡先
router_cc.png

#プロジェクトの作成#

npx create-react-app proj01

インストールされたモジュールの確認

cd proj01
$ npm list --depth=0
proj01@0.1.0 /home/uchida/tmp/feb14/proj01
├── @testing-library/jest-dom@5.16.2
├── @testing-library/react@12.1.2
├── @testing-library/user-event@13.5.0
├── react-dom@17.0.2
├── react-scripts@5.0.0
├── react@17.0.2
└── web-vitals@2.1.4

react-router-dom をインストール

npm install react-router-dom

バージョンを確認

$ npm list --depth=0
proj01@0.1.0 /home/uchida/tmp/feb14/proj01
├── @testing-library/jest-dom@5.16.2
├── @testing-library/react@12.1.2
├── @testing-library/user-event@13.5.0
├── react-dom@17.0.2
├── react-router-dom@6.2.1
├── react-scripts@5.0.0
├── react@17.0.2
└── web-vitals@2.1.4

次のプログラムを差し替えます。

src/App.js
src/index.js
src/App.js
import { Routes, Route } from 'react-router-dom';

import Home from './routes/home';
import About from './routes/about';
import Contact from './routes/contact';
import NoMatch from './routes/nomatch';

function App() {
  return (
    <div className="App">
      <h1>Hello React Router v6</h1>
<ul>
        <li>
          <a href="/">ホーム</a>
        </li>
        <li>
          <a href="/about">紹介</a>
        </li>
        <li>
          <a href="/contact">連絡先</a>
        </li>
      </ul>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
	 <Route path="*" element={<NoMatch />} />
      </Routes>
    </div>
  );
}

export default App;
src/index.js
import ReactDOM from 'react-dom';
import App from './App';

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

次のコードを作成します。

src/routes/home.js
src/routes/about.js
src/routes/contact.js
mkdir src/routes
src/routes/home.js
function Home() {
  return <h2>トップページ</h2>;
}

export default Home;
src/routes/about.js
function About() {
  return <h2>このページについて</h2>;
}

export default About;
src/routes/contact.js
function Contact() {
  return <h2>連絡先のメールアドレス</h2>;
}

export default Contact;

サーバーの起動

npm start

ブラウザーで、
http://localhost:3000
にアクセス

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?