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?

【React】Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-router-dom.js?v=7b3f53dc' does not provide an export named 'Switch' の対処法

0
Posted at

はじめに

StackBlitzというWeb上の統合開発環境を使ってReactの学習中、「react-router-dom」を使ってルーティング制御を行なっていた時に起こった出来事。

問題

以下のソースコードを記述すると、突如画面が真っ白になった。

デベロッパーツールのコンソールを見てみると、タイトルのエラー表示が出ていた。

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Top } from '../components/pages/Top';
import { Users } from '../components/pages/Users';
import { DefaultLayout } from '../components/templates/DefaultLayout';

export const Router = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/">
          <DefaultLayout>
            <Top />
          </DefaultLayout>
        </Route>
        <Route path="/users">
          <Users />
        </Route>
      </Switch>
    </BrowserRouter>
  );
};

スクリーンショット 2025-12-28 112820.png

解決方法

「react-router-dom」のバージョン違いによる起こったエラーでした。

使用している教材通りにコーディングを行なっていましたが、私の環境のバージョンだと非推奨の書き方になるようです。

・教材のバージョン5.2.0
・実際にインストールしたバージョン7.10.1

以下のようにバージョン6以降で推奨されている書き方に編集すると、画面が表示されました。

・Switch → Routes
・exact → (削除)
・表示したいコンポーネントはelementで囲う

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { Top } from '../components/pages/Top';
import { Users } from '../components/pages/Users';
import { DefaultLayout } from '../components/templates/DefaultLayout';

export const Router = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          path="/"
          element={
            <DefaultLayout>
              <Top />
            </DefaultLayout>
          }
        />
        <Route path="/users" element={<Users />} />
      </Routes>
    </BrowserRouter>
  );
};

image.png

おわりに

教材ではどのバージョンを使用しているのかしっかり確認して、最新のバージョンだと書き方に違いはあるか、調べながら今後も学習していこうと思いました。

参考

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?