Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is must to import "react" even if my client.js is not using it

Tags:

reactjs

I am learning React and got little confused when my code didn't work when I didn't imported "React" in my client.js. Ideally when I am not using "React" in my code therefore I should not forced to import "react" module. Following is code snippet.

Layout.js:

import React from "react";

export  default class Layout extends React.Component {
  constructor () {
    super();
    this.name = "Dilip";
  }
  render () {
    return (
      <h1>Welcome {this.name} in React world !!</h1>
    )
  }
}

Working code:

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

import  Layout from "./components/Layout"

const app = document.getElementById('app');
ReactDOM.render(<Layout/>, app);

Not working Code:

import ReactDOM from "react-dom";

import  Layout from "./components/Layout"

const app = document.getElementById('app');
ReactDOM.render(<Layout/>, app);

Why it doesn't work when I removed code to import "React"? I am not using "React" anywhere therefore it should work. It throws following error in console.

Uncaught ReferenceError: React is not defined

Note: I am following video

like image 378
joy Avatar asked Dec 14 '22 07:12

joy


1 Answers

@Matteo is wrong. Though ReactDOM does depend on React, it is requiring it itself in its code.

The reason why you need to import React, is the JSX snippet :

<Layout/>

Which is only syntactic sugar for :

React.createElement(Layout)

Therefore, after JSX compilation, React is effectively needed. ;)

like image 181
yachaka Avatar answered Jan 11 '23 11:01

yachaka