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?

<Switch>を使ったら画面が真っ白になった

1
Posted at

はじめに

<Switch>は廃止されていました。

問題

<Switch>を使ったら画面が真っ白になりエラーになった。

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

export const Router = () => {
  return (
    <Switch>
      <Route path="/">
        <Home />
      </Route>
      <Route path="/page1/">
        <Page1 />
      </Route>
      <Route path="/page2/">
        <Page2 />
      </Route>
      <Route path="/page1/detailA">
        <Page1DetailA />
      </Route>
      <Route path="/page1/detailB">
        <Page1DetailB />
      </Route>
      <Route path="/page2/:id">
        <UrlParameter />
      </Route>
      <Route path="*">
        <Page404 />
      </Route>
    </Switch>
  );
};

解決方法

<Switch>はreact-router-dom v6で廃止されました。
v6では<Routes>に置き換わっています。
また、子要素の記述方法もelementプロパティに変更する必要があります。

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

export const Router = () => {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/page1/" element={<Page1 />} />
      <Route path="/page2/" element={<Page2 />} />
      <Route path="/page1/detailA" element={<Page1DetailA />} />
      <Route path="/page1/detailB" element={<Page1DetailB />} />
      <Route path="/page2/:id" element={<UrlParameter />} />
      <Route path="*" element={<Page404 />} />
    </Routes>
  );
};

おわりに

react-router-dom v6では<Switch>が廃止され、<Routes>に統一されました。
あわせてコンポーネントの渡し方も子要素からelementプロパティへの変更が必要です。
v5から移行する際はご注意ください。
同じエラーで詰まった方の参考になれば幸いです。

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?