1
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 1 year has passed since last update.

事前情報

業務でReactを使う機会が出たため、2021年あたりの教材を用いて勉強を開始しました。しかし、表題のエラーに四苦八苦したため備忘録として残しておきます。

環境

学習教材

  • ruby: 2.7.0
  • rails: 6.1.4.1
  • react: 17.0.1
  • react-router-dom: 5.2.0

ローカル環境

  • ruby: 3.0.2
  • rails: 7.1.3
  • react: 18.2.0
  • react-router-dom: 6.21.3

※一部抜粋

エラー内容

実装コード Sample.js

import { Switch, Route, Link } from 'react-router-dom'
~~(省略)~~
function Sample() {
  return (
~~(省略)~~
      <Wrapper>
        <Switch>
          <Route exact path="/samples" component={SampleList} />
          <Route exact path="/samples/new" component={AddSample} />
          <Route path="/samples/:id/edit" component={EditSample} />
        </Switch>
      </Wrapper>
~~(省略)~~

画面表示したときに下記エラーが出た。
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Sample`.

原因

React Router v5→v6へのVersionUpにより、ルートやコンポーネントの指定が下記の通り変更されていた。
以下、コードの修正版を参考までに載せるが、変更箇所は下記の通り。
  • react-router-domのimport文ではSwitchではなくRoutesを指定し、<Switch><Routers>に変更。
  • コンポーネントの指定をcomponent={コンポーネント名}ではなく、element={<コンポーネント名 />}で指定する。
import { Routes, Route, Link } from 'react-router-dom'
~~(省略)~~
function Sample() {
  return (
~~(省略)~~
      <Wrapper>
        <Routes>
          <Route exact path="/samples" element={<SampleList />} />
          <Route exact path="/samples/new" element={<AddSample />} />
          <Route path="/samples/:id/edit" element={<EditSample />} />
        </Routes>
      </Wrapper>
~~(省略)~~

まとめ

勉強する場合はVersionの違いに気を付けようということでした...
GithubCopilotも使っていたんですが、回答を見てもどこもおかしなところがなく完全にはまってしまいました。Versionの違いも入れて質問すればよかったといまさらながら思いました。
コメント、指摘あればいただければ幸いです。
1
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
1
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?