The error "React must be in scope when using JSX" occurs because JSX syntax is transformed into React.createElement calls by the compiler, so the React variable must be available in the file using JSX.
Explanation of the Error
JSX is not understood by browsers directly; it needs to be compiled into JavaScript. In versions of React prior to 17, JSX is compiled into calls to React.createElement. As a result, React must be imported in every file that uses JSX:
javascript
import React from 'react';
Without this import, the React identifier is not in scope, causing the error when JSX is used.
Changes in React 17 and Later
Starting with React 17, a new JSX transform was introduced that automatically imports the necessary React functions when JSX is used. This means importing React explicitly in every file is no longer required if the project is configured to use the new JSX transform. However, if ESLint or the build setup is not updated to recognize this, the error might still appear. To fix, update ESLint to turn off the rule enforcing React in scope for JSX:
json
"rules": {
"react/react-in-jsx-scope": "off",
"react/jsx-uses-react": "off"
}
Or ensure that the React version and react-scripts packages are updated to support the new JSX transform.
Summary
- Pre React 17: Must
import React from 'react';
in every file using JSX. - React 17 and Later: Import not required if using the new JSX transform; update ESLint and build tools if needed to avoid the error.
- Check that your React, React-DOM, and react-scripts versions are up to date.
- Make sure your JSX files have the correct
.jsx
or.js
extensions and your project supports JSX syntax properly.
This error essentially ensures that the JavaScript environment recognizes React as a variable when JSX is compiled into JavaScript function calls involving React.