🐈
react-router-dom v5 / v6 おぼえ書き
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>
);
};
Discussion