"React must be in scope when using JSX" (react/react-in-jsx-scope with "window.React = React" on index.js)

ohkts11 picture ohkts11 · Mar 17, 2018 · Viewed 16.9k times · Source

I am following Chapter 5, "React with JSX", of "Learning React" from O'Reilly.

I wrote the Recipes App using create-react-app as the base.

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';

import App from './App';
import Menu from './Menu';

import registerServiceWorker from './registerServiceWorker';

import data from './data/recipes';

window.React = React;

ReactDOM.render(<Menu recipes={data} />, document.getElementById('root'));

registerServiceWorker();

Menu.js

import Recipes from './Recipes';

const Menu = ({recipes}) => (
    <article>
        <header>
            <h1>Delicious Recipes</h1>
        </header>
        <div className = "recipes">
        {recipes.map((recipe, i)=>    
            <Recipes key={i} {...recipe}  />
        )}
        </div>
    </article>
);

export default Menu;

And have the following error:

Failed to compile ./src/Menu.js
  Line 5:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 6:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 7:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 9:   'React' must be in scope when using JSX  react/react-in-jsx-scope
  Line 11:  'React' must be in scope when using JSX  react/react-in-jsx-scope
    
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.

The book says "setting window.React to React exposes the React library globally in the browser. This way all calls to React.createElement are assured to work". But it seems like I still need to import React on each file that uses JSX.

Answer

Eduard picture Eduard · Mar 17, 2018

Import React on top of your Menu.js file:

import React from 'react'

React should always be imported in a particular file, that uses JSX if you are working with this library (React) in your project.