0
0

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 3 years have passed since last update.

【React】You should not use <Link> outside a <Router>の対処法

Posted at

症状

react-router-domのLinkを使用としたとき、下記エラーが発生してしまいました。 翻訳すると 「 を の外で使用しないでください」でした。
error
Error: Invariant failed: You should not use <Link> outside a <Router>
App.jsx
import React,{ Fragment } from "react";
import './App.css';
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";
import HogeIndex  from "HogeIndex";
import Hoge from "Hoge";
import { Link } from "react-router-dom";

function App() {
  return (
    <Fragment>
    <Link to={`/`}>
    <Router>
      <Switch>
        <Route
          exact
          path="/">
          <HogeIndex />
        </Route>
          }
        >
        </Route>
        <Route
          exact
          path="/hpge">
          <Hoge />
        </Route>
          }
        >
        </Route>
      </Switch>
    </Router>
    </Fragment>
  );
}

export default App;

解決策

Linkタグを内部に入れたら、解決しました。 構成上Router外部から、ページ遷移させたい場合はhistoryを使ったりするようです。 下記参照

参考

https://teratail.com/questions/134856
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?