7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

react-router-domのv5, v6の違い

Posted at

react-router-domのv5, v6の記述方法に若干違いがあるので紹介していきます。

Switch → Routes に変更

  • v5では、RouteをSwitchで囲みますが、v6では、SwitchをRoutesに変えます。

Route内の記述方法

  • Route内の記述方法ですが、v5ではexact component={遷移先コンポーネント}のように書いていましたが、v6では exactはいらなくなり、element={<遷移先コンポーネント />} のように書きます。

上記をコードに書くと下記のようになります。


v5の場合

app.js
import React from 'react';
import { Container } from '@material-ui/core';
import { BrowserRouter, Switch, Route } from 'react-router-dom'; //Switch

import Navbar from './components/Navbar/Navbar';
import Home from './components/Home/Home';
import Auth from './components/Auth/Auth';

const App = () => {
  return (
    <BrowserRouter>
      <Container maxWidth="lg">
        <Navbar />
        <Switch> //v5
          <Route path="/" exact component={Home} />  //v5
          <Route path="/auth" exact component={Home} /> //v5
        </Switch>
      </Container>
    </BrowserRouter>
  );
};

export default App;


v6の場合

app.js
import React from 'react';
import { Container } from '@material-ui/core';
import { BrowserRouter, Routes, Route } from 'react-router-dom'; //Routes

import Navbar from './components/Navbar/Navbar';
import Home from './components/Home/Home';
import Auth from './components/Auth/Auth';

const App = () => {
  return (
    <BrowserRouter>
      <Container maxWidth="lg">
        <Navbar />
        <Routes> //v6
          <Route path="/" element={<Home />} /> //v6
          <Route path="/auth" element={<Auth />} /> //v6
        </Routes>
      </Container>
    </BrowserRouter>
  );
};

export default App;


##useHistory → useNavigate に変更

index.js
import { useHistory } from 'react-router-dom'; //v5
import { useNavigate } from 'react-router-dom'; //v6

// v5
const history = useHistory();
history.push("/");
history.goBack();

// v6
const navigate = useNavigate();
navigate("/");
navigate(-1);

##まとめ
個人的にはv6になって直感的に書きやすいなと思っています!
他にも詳しく知りたい方がいれば、下記のリンクを参考にしてみて下さい!

##参考
https://dev.classmethod.jp/articles/react-router-5to6/

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?