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

React Router v7のネストしているルーティングの書き方

Posted at

はじめに

UdemyでReactを学んでいる中で、動画でReact Routerの流れをバージョン5系で学んだあとに、最新バージョンに挑戦した所、困ったので投稿します。

環境

  • StackBlitz
  • react 19.2.3
  • react-dom 19.2.3
  • react-router-dom 7.13.0

問題

Atomicデザインで親コンポーネント内に子コンポーネントをネストしたかったのですが、下記のように記述しても親コンポーネントだけ表示されました。

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { Parent } from '../components/Parent';
import { Child } from '../components/Child';
export const Router = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route element=<Parent />>
          <Route index element=<Child /> />
        </Route>
      </Routes> 
    </BrowserRouter>
  );
};

解決方法

親コンポーネント内に<Outlet />を記述するだけで解決することができました。

Parent.jsx
import { Outlet } from 'react-router-dom';

export const Parent = (props) => {
  const { children } = props;
  return (
    <>
      {children}
      {/* ルーティングでネストする時は必須 */}
      <Outlet />
    </>
  );
};

おわりに

v5 から v6あたりで書き方が大きく変わっているので、公式ドキュメントを見てしっかりと差分を確かめようと思います。

参考

公式ドキュメント

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