Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSX can be used without importing React

I'm trying to run my first React JSX file with create-react-app with version 4.0.0 and it works! However, I don't have the import statements of React included in my JSX and it works too but it is very weird. The project is created by create-react-app command with version 4.0.0.

The App.js file:

/* without import React but works too! */

 import { Component } from "react";
class App extends Component {
  render() {
    return <div>456</div>;
  }
}
export default App;
like image 789
Thomas.lin Avatar asked Oct 26 '20 16:10

Thomas.lin


People also ask

Can we use JSX in React?

React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

Can you use JSX without Babel?

React doesn't require babel but the library is built on the concept of using ES6 javascript syntax. React app however can be built with old ES5 syntax and JSX which would remove the need for Babel but you would lose the potential benefits of ES6.

What is JSX used for in React?

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

Why do I need to import React?

Explanations: The JSX gets internally into many React. createElement() function calls and each of them returns an object as shown above. Now because of this, we need to import React from “react” since internally every JSX is creating a React Component using JSX transformer.


1 Answers

Starting from React 17 it's not necessary to import React to use JSX. See from the blog post about that in the section called Removing Unused React Imports:

Because the new JSX transform will automatically import the necessary react/jsx-runtime functions, React will no longer need to be in scope when you use JSX. This might lead to unused React imports in your code.

What’s a JSX Transform?

Browsers don’t understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript.

Suggested read is Introducing the New JSX Transform. Also you can see Using React 17 and the new JSX transform with Create React App 4.0 Alpha.

like image 106
norbitrial Avatar answered Sep 23 '22 12:09

norbitrial