Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 866
ohkts11 Avatar asked Mar 17 '18 12:03

ohkts11


2 Answers

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.

like image 127
Eduard Avatar answered Oct 21 '22 18:10

Eduard


This happens due to “React” import necessary in JSX file. The React library must also always be in scope from JSX code because JSX compiles as a react.

in your case 'React' must be import in Menu.js,

import React from "react"; 

this is an error most beginner react developers made.

And also You can refer

like image 29
ricky Avatar answered Oct 21 '22 20:10

ricky