Thomas.lin
Thomas.lin

Reputation: 440

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;

Upvotes: 16

Views: 25717

Answers (3)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

import React from 'react';

function App() {
  return <h1>Hello World</h1>;
}

Earlier react jsx used to transform element using React.createElement(). There was no automatic insertion:

import React from 'react';

function App() {
  return React.createElement('h1', null, 'Hello world');
}

Now, jsx is transpiled by a compiler automatically.

// Inserted by a compiler
import {jsx as _jsx} from 'react/jsx-runtime';

function App() {
  return _jsx('h1', { children: 'Hello world' });
}

Thus, we don't need to import React component unless we need to use React explicitly. For eg.

import React from 'react' // without it, compiler will fail
class Foo extends React.Component {
 render() {
   return <h1>hello</h1>
 }
}

Upvotes: 0

norbitrial
norbitrial

Reputation: 15166

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.

Upvotes: 25

trixn
trixn

Reputation: 16309

This is new with the JSX transform introduced with React 17 :

Together with the React 17 release, we’ve wanted to make a few improvements to the JSX transform, but we didn’t want to break existing setups. This is why we worked with Babel to offer a new, rewritten version of the JSX transform for people who would like to upgrade.

Upgrading to the new transform is completely optional, but it has a few benefits:

  • With the new transform, you can use JSX without importing React.
  • Depending on your setup, its compiled output may slightly improve the bundle size.
  • It will enable future improvements that reduce the number of concepts you need to learn React.

Upvotes: 11

Related Questions