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-domでswitchを使うと下記エラーがでた。
原因と対応をメモする。

[BabelError] /Users/apple/Desktop/JISOU/stepup-react/src/App.jsx: Unexpected keyword 'switch'. (2:30)

  1 | import "./App.css";
> 2 | import { BrowserRouter, Link ,switch} from "react-router-dom";
    |                               ^
  3 | import { Home } from "./Home";
  4 | import { Page1 } from "./Page1";
  5 | import { Page2 
} from "./Page2";
unknown file:2:30

環境

  • react-router-dom: 7.16.0

原因

react-router-domでswitchが使えるのはv5まで、今回v7は対象外。v6からRoutesになったようですね。
v6移行時、いろいろ変更になったみたいです。

解決

Routesにしたら無事に解決!

import "./App.css";
import { BrowserRouter, Link, Route, Routes } from "react-router-dom";
import { Home } from "./Home";
import { Page1 } from "./Page1";
import { Page2 } from "./Page2";
import { Page1DetailA } from "./Page1DetailA";
import { Page1DetailB } from "./Page1DetailB";

function App() {
  return (
    <>
      <BrowserRouter>
        <Link to="/">HOME</Link>
        <br />
        <Link to="/Page1">Page1</Link>
        <br />
        <Link to="/Page2">Page2</Link>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/Page1" element={<Page1 />} />
          <Route path="/Page1/DetailA" element={<Page1DetailA />} />
          <Route path="/Page1/DetailB" element={<Page1DetailB />} />
          <Route path="/Page2" element={<Page2 />} />
        </Routes>
      </BrowserRouter>
    </>
  );
}

終わりに

こちらのエラー記事はたくさんあって、わかりやすかった!
公式ページも見つつ仕様確認していきたいですね。

参考

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?