Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why should we use import React from 'react' [duplicate]

i am learning React js in case ii App.js module i have to import React because the render() method is used to convert JSX to dom elements how ever in Person.js we are creating a arrow function and we are exporting it so that it can be imported and used in the App modules render function how ever in App module we have React imported and it will convert the JSX in module person and gets rendered on DOM but when it throws an error when we remove the below code in Person.js

import React from 'react' in Person.js

it throws error

React' must be in scope when using JSX if we declare JSX in the methods (like render ) provided from React class it should give an error.

can someone please explain

i)why do we need to import react in Person.js?

ii)why was it throwing error when we remove the above code?

case i)

Person.js

 import React from 'react'

 const person = () => {
 return <p>This is person module used inside app module</p>
 };

 export default person

case ii)

App.js

import React, { Component } from 'react';
import './App.css'
import Person from './Person/Person'

class App extends Component {
render() {
return (
  <div className="App">
    <h1>this is app module and i am being used as the root component</h1>
     <Person/>
  </div>
);}}

export default App;
like image 451
electrodragon Avatar asked Jul 17 '18 19:07

electrodragon


2 Answers

When you are trying to use jsx in your javascript file your normal compiler as well as even babel couldnot understand it. Although normal compiler never understand it. But anyhow you want to say your compiler I am providing you a jsx in the file.

import React from 'react';

Above is the way to instruct babel go on, its a easy task for you now.

<p>This is person module used inside app module</p>

Above is a jsx statment. So when ever you use it you will require React imported. Similarly we donot need it in actions, reducers and so on in many places because we dont have jsx there.

like image 33
Shubham Agarwal Bhewanewala Avatar answered Sep 18 '22 00:09

Shubham Agarwal Bhewanewala


If you give some JSX to Babel, you will see that JSX is just sugar for React.createElement calls. This is why we need to import React if we use JSX.

Input

<p>This is person module used inside app module</p>

Output

/*#__PURE__*/
React.createElement("p", null, "This is person module used inside app module");
like image 131
Tholle Avatar answered Sep 19 '22 00:09

Tholle