🦖

Next.js(React.js)の'Component' cannot be used as a JSX component.の解決方法

2022/06/20に公開

Nextjsでかんたんなサイトを作ろうと思っていると、Next.jsのpageのベースとなるファイルである_app.tsxというファイルでこんなエラーがビルド時に表示されて困りました。

1日これで潰したかもしれないくらいハマりました。

Type error: 'Component' cannot be used as a JSX component.

前提

ツールやアプリのバージョンは以下です。

TH バージョン 確認方法
docker 20.10.14 コマンド(docker -v)で確認
Node 14.17.0 Dockerfileで確認
Next.js 12.1.4 package.jsonより
yarn 1.22.5 コマンド(yarn -v) で確認

「Type error: 'Component' cannot be used as a JSX component.」とは?

ここで書いているエラーを読んでみると、「ComponentがJSXコンポーネントとして使われてないですよ」とというエラーみたいです。

Type error: 'Component' cannot be used as a JSX component.

このエラーが発生しているファイルである _app.tsx にtailwind cssを有効にしたくらいしか変更していないのでよくわからず、なんの手がかりにもなりませんでした。

_app.tsx
import '../styles/globals.css';
import React from 'react';
import type { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

export default MyApp

vscodeが勝手に警告しているだけかと思い、(yarn build)ビルドをしてみましたけど、結果は同じでした。

./pages/_app.tsx:7:6
Type error: 'Component' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<{}, any, any> | null' is not a valid JSX element.
    Type 'Component<{}, any, any>' is not assignable to type 'Element | ElementClass | null'.
      Type 'Component<{}, any, any>' is not assignable to type 'ElementClass'.
        The types returned by 'render()' are incompatible between these types.
          Type 'React.ReactNode' is not assignable to type 'import("/usr/src/app/node_modules/@types/react-dom/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.

   5 | function MyApp({ Component, pageProps }: AppProps) {
   6 |   return (
>  7 |     <Component {...pageProps} />
     |      ^
   8 |   );
   9 | }
  10 | 
error Command failed with exit code 1.

解決策

package.jsonresolutionsで依存関係を解決しました。

解決はできたけども、なぜこれでうまくいくのかはよくわかりませんでした。(もう少し調査する必要がありますね。)

package.json
"dependencies": {
		"react": "18.0.0",
    "react-dom": "18.0.0"
},
"resolutions": {
   "@types/react": "17.0.40"
},
"devDependencies": {
  	"@types/react": "17.0.14",
    "@types/react-dom": "17.0.14"
}

https://zenn.dev/choco14t/scraps/e0179b898b7f54

https://chore-update--yarnpkg.netlify.app/ja/docs/selective-version-resolutions

カラビナテクノロジー デベロッパーブログ

Discussion