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-routerでnavを作成する

Last updated at Posted at 2023-08-24

現在、未経験からフロントエンド転職を目指し学習中のもうすぐアラサー会社員です

React?SPA?わからんが??ナビゲーションどうすりゃええんや??という状態から
ナビゲーションバーをなんとか作成したので個人的備忘録的な投稿です

※情報には誤りが含まれる可能性があります(ぜひご指摘いただきたいです!)

1. インストール

  

npm
$ npm i react-router-dom

create-react-appやviteなど使用した場合はcssやApp.jsの中身要らないので消しておきます

  

2. BrowserRouter

いろいろインポートした後BrouserRouterでAppコンポーネントを囲みます
仕組みについて全然わかっていませんが、その内調べて記事にしようと思います

ReactRouterドキュメント

main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
)

3. componentsの作成

navを含めページのcomponentを作成します
aタグはLinkに、'href'は 'to'になるので注意!
  

Nav.jsx

<Link to="/hoge"> Hoge </Link>

4. ルーティング

ルーティングはRoutes, Routeを使用します
古い記事ではSwitchが使用されていましたが、インポートできないので注意
  

App.jsx
        //ナビゲーションコンポーネント
        <Nav />

        <Routes>
            <Route exact path='/' element={<Home />} />
            <Route path='/hoge1' element={<Hoge1 />} />
            <Route path='/hoge2' element={<Hoge2 />} />
            <Route path='/hoge3' element={<Hoge3 />} />
          </Routes>

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?