1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Router v6でのネストの書き方で詰まったところ

Last updated at Posted at 2024-08-13

はじめに

React Router v6の書き方で特に詰まったところを上げたいと思います

コンポーネントの配下にコンポーネントをレンダリングする場合

v5での書き方

v5の場合はswitchの中でRouteを設定し、親コンポーネントの配下に子コンポーネントをレンダリングし、それをSwitch文で囲っていました。

import { BrowserRouter, Switch, Route } from "react-router-dom";

<BrowserRouter>
  <Switch>
    <Route exact path="/">
      <ParentComponent>
        <ChildComponent />
      </ParentComponent>
    </Route>
  </Switch>
</BrowserRouter>

v6からの書き方

v6からはRoutesで囲み、elemntの中で親コンポーネントの配下の子コンポーネントをレンダリングするようになりました。

import { BrowserRouter, Routes, Route } from "react-router-dom";

<BrowserRouter>
  <Routes>
    <Route
      path="/"
      element={
        <ParentComponent>
          <ChildComponent />
        </ParentComponent>
      }
    />
  </Routes>
</BrowserRouter>

終わりに

elemntの中でネストできることを知らず、詰まってしまいました。
React Router v6の書き方を覚えていきたいです。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?