- Instant help with your JavaScript coding problems

Fix the 'React' must be in scope when using JSX error

In today's modern React-based applications that use version 17 or later (e.g. NextJS 13, create-react-app 5), a common ESLint bug is:

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

 

Why does this error occur?

Prior to React 17, all JSX code was compiled by the transpiler (TypeScript, Babel) into a React.createElement . As you can immediately see we are talking about a React object with a capital R in the compiled code that needs to be imported. However, in React 17 a new JSX transpile option has been introduced, which when used no longer generates the React.createElement code, but a _jsx call. So far, this does not require the React object. For modern React frameworks, such as NextJs 13, this new method is now the default, so there is no need for a constant import line of code.
But here comes the twist if you're also using ESLint in your project. Because ESLint will report an error by default if it can't find the React import. 

Solution

There are a number of suggested solutions on the web, but not all of them are recommended. The following suggestions assume you are using React 17 or later with the react-jsx compile option.

Disable the ESLint rule

This is a not recommended solution. It does indeed remove the bug, but it is not a good approach to fixing bugs by turning off warning messages.
If you still want to use this override, you should extend the rules property in the ESLlint configuration file (.eslintrc.json) with the entry "react/react-in-jsx-scope": "off"

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

Import React

The problem can also be solved by importing the React (with capital R ) library at the beginning of the file like this: 

import React from 'react';

This is not only unnecessary code, but could also be a source of another warning in the future because the import is not actually used.

Setting up ESLint correctly

Finally, let me show you what I think is the correct solution. This is to use the correct ESLint plugin. Yes, there is a separate plugin for the new JSX transformation. To do this, you also need to modify the ESLint configuration file, but now you need to add the line "plugin:react/jsx-runtime" to the extends array. 

{
  "extends": [
    ...
    "plugin:react/jsx-runtime",
  ],

}

Resources

ESLint rule reference

React new JSX transform

 

Share "Fix the 'React' must be in scope when using JSX error" with your friends