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

【ESLint】React' must be in scope when using JSXの解決方法

Last updated at Posted at 2024-09-08

はじめに

React開発でESLintを設定している際に、「'React' must be in scope when using JSX」というエラーに遭遇したので、解決までの過程をまとめます。

'React' must be in scope when using JSX  react/react-in-jsx-scope

修正前のファイルがこちらです。

export default [
  { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
  { languageOptions: { globals: globals.browser },
    pluginJs.configs.recommended,
    ...tseslint.configs.recommended,
    pluginReactConfig,
  },
];

警告
現在PrettierとESLintの設定を勉強している途中ですので誤まった解決策である場合があると思います。その場合はぜひご指摘いただけると幸いです。(2024年9月現在)

原因

このエラーは、ESLintがJSXを使用する際に、Reactがスコープ内に存在することを要求しているために発生します。一般的には、App.tsxなどのコンポーネントファイルの先頭にimport React from 'react';と記述することで解決しますが、今回のケースでは、ESLintの設定に問題がありました。

App.tsx
import React from 'react';

解決策

エラーを無視する設定の追加

今回はESLint側でこちらのエラーを無視する設定を追加します。

rules: {
  "react/react-in-jsx-scope": "off",
  "react/jsx-uses-react": "off",
},

この設定を追加することで、ESLintは上記のエラーを無視するようになります。

設定の順序の変更:

ESLintの設定の順序によって、ルールが適用される順番が変わり、意図しない結果になることがあります。今回のケースでは、pluginReactConfigの設定を他の設定よりも前に移動することで、エラーが解消されました。

export default [
  { files: ["**/*.{js,mjs,cjs,ts,jsx,tsx}"] },
  //移動
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  pluginReactConfig,
  //
  { languageOptions: { globals: globals.browser },
    //追加
    rules: {
      "react/react-in-jsx-scope": "off",
      "react/jsx-uses-react": "off",
    },
    //
  },
];

終わりに

ESLintについてまだまだわからないことがたくさんあるので間違いがあれば、ぜひご指摘いただけると幸いです。

参考

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