備忘録

備忘録

react-bootstrapとreact-router-domを同時に使う方法

Ⅰ. はじめに

タイトルの通り「react-bootstrapとreact-router-domを同時に使う方法」です。

Ⅱ. やり方

1. 必要なライブラリをインストールする
npm i -D bootstrap react-bootstrap react-router-dom react-router-bootstrap
2. ファイルを編集する

src/main.tsx

import 'bootstrap/dist/css/bootstrap.min.css'
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import { router } from './Router'

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <RouterProvider router={router} fallbackElement={<p>Loading...</p>} />
  </React.StrictMode>,
)

src/App.tsx

import { Outlet } from 'react-router-dom'
import { Container } from 'react-bootstrap'
import { MyNavbar } from './MyNavbar'

export function App() {
  return (
    <>
      <MyNavbar />
      <Container>
        <Outlet />
      </Container>
    </>
  )
}

src/Router.tsx

import { createBrowserRouter } from 'react-router-dom'
import { App } from './App'
import { Page001 } from './components/Page001'
import { Page002 } from './components/Page002'

export const router = createBrowserRouter([
  {
    path: '/',
    element: <App />,
    children: [
      { index: true, element: <Page001 /> },
      { path: '/', element: <Page001 /> },
      { path: '/page002', element: <Page002 /> }
    ]
  }
])

src/components/Page001.tsx

export function Page001() {
  return (
    <span>Page001</span>
  )
}

src/components/Page002.tsx

export function Page002() {
  return (
    <span>Page002</span>
  )
}

src/MyNavbar.tsx

import { Nav, Navbar } from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'

export function MyNavbar() {
  return (
    <Navbar bg="dark" variant="dark" expand="lg">
      <LinkContainer to="/">
        <Navbar.Brand>Navbar</Navbar.Brand>
      </LinkContainer>
      <Navbar.Toggle aria-controls="basic-navbar-nav" />
      <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="me-auto">
          <LinkContainer to="/">
            <Nav.Link>Page001</Nav.Link>
          </LinkContainer>
          <LinkContainer to="/page002">
            <Nav.Link>Page002</Nav.Link>
          </LinkContainer>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  )
}

実行結果