11
1

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, TypeScript】「cannot be used as a JSX component...」エラー

Posted at

環境

  • Mac OSX: v11.2.1
  • node: v16.15.1
  • yarn: v1.22.18

エラー詳細

  • yarn start でコンパイルを試みたところ、以下のエラーにより失敗
    ('Menu'semantic-ui-react からインポートしたコンポーネント)
TypeScript error in /xxxx/App.tsx(28,8):
'Menu' cannot be used as a JSX component.
  Its instance type 'Component<MenuProps, any, any>' is not a valid JSX element.
    The types returned by 'render()' are incompatible between these types.
      Type 'React.ReactNode' is not assignable to type 'import("/Users/ayakahidaka/Documents/random-training-timer-front/node_modules/@types/react-dom/node_modules/@types/react/index").ReactNode'.  TS2786

    26 |   return (
    27 |     <div>
  > 28 |       <Menu 
       |        ^
    29 |         as={Menu}
    30 |       >
  • エラー発生時の package.json(一部抜粋)
{
  "dependencies": {
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "react": "^17.0.0",
    "react-dom": "^17.0.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    ...
  }
  ...
}

解決方法

"resolutions": {
  "@types/react": "^17.0.0"
}

解説

解決前後の変化

  • 参考にしたサイト内の解説によると、@types/react-dom@types/react のメジャーリリースバージョンに依存するとのこと
    • package.json で指定した @types/react のバージョンには依存しない模様
  • 修正前後の yarn.lock を比較すると確かに解説通り(左: 修正前、右: 修正後)
    スクリーンショット 2022-06-06 21.55.32.png

resolutionsとは?

Yarn supports selective version resolutions, which lets you define custom package versions or ranges inside your dependencies through the resolutions field in your package.json file. Normally, this would require manual edits in the yarn.lock file.

  • yarnで依存関係に用いるカスタムパッケージのバージョンを指定できる
  • yarn.lockを直接編集せず、package.json 内に記述することで実現可能

参考サイト

11
1
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
11
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?