React works without importing it

Viewed 896

I am confusing about the import React statement. I know that if we need to use JSX we need to import the React from the react package.

import { Count } from "./components/Count";

// import React, { useState } from "react";
function App() {
  const visiable = true;
  return (
    <div>
      <Count visiable={visiable} />
      {/* <button
        onClick={() => {
 
        }}
      >
        Switch
      </button> */}
    </div>
  );
}

export default App;

in the code example above, isnt that the return data are JSX? I have div, button and Counter component inside return statement. If I understand correctly, these are JSX.

But I did not import the React inside the file. But it's still compiled successfully. May someone help me understand this. Thanks

2 Answers

UPDATE: This answer was based off of my old understanding of JSX. React has recently introduced a new way for JSX to compile, which has made importing React optional. If you're using the new JSX transform (which is used by default in the current version of create-react-app), then this answer does not apply, refer to @kind-user's answer.

It can technically compile just fine, but it won't run.

When it compiles the jsx, it basically turns something like return <div>Hello World!</div> into something like:

return React.createElement('div', null, 'Hello World!');

which uses the React object, so if React isn't in the namespace, then you'll just get runtime errors. Unless ... your React object is a global variable accessible anywhere.

Related