🐈

react-router-dom v5 / v6 おぼえ書き

2022/12/24に公開

react-router-domはv5 / v6で少し書き方が違う。バージョンアップデートでSwitchが廃止されRoutesが導入された影響。このことを知らなくてしばらく目が死んだ魚のようになった😇

v5の書き方(Switchを使う)

// Switchをimport
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Home from "./Home";
import Register from "./Register";
import Login from "./Login";
import NotFound from "./NotFound";

const App = () => {
  return (
    <BrowserRouter>
      <Switch> {/* Switch で囲む */}
        <Route exact path={`/`} component={Home} />
        <Route path={`/register/`} component={Register} />
        <Route path={`/login/`} component={Login} />
        <Route path={`/*/`} component={NotFound} />
      </Switch>
    </BrowserRouter>
  );
};

v6の書き方(Switchの代わりにRoutesを使う)

// Routesをimport
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
import Register from "./Register";
import Login from "./Login";
import NotFound from "./NotFound";

const App = () => {
  return (
    <BrowserRouter>
      <Routes> {/* Routes で囲む */}
        <Route path={`/`} element={<Home />} />
        <Route path={`/register/`} element={<Register />} />
        <Route path={`/login/`} element={<Login />} />
        <Route path={`/*/`} element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
};

https://ralacode.com/blog/post/how-to-use-react-router/

https://zenn.dev/longbridge/articles/65355d3fdb7939

Discussion