2
votes

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
It's probably working because you already imported React in another component or file so in the final compiled javascript the dependency exists, but you should not rely on this and you should always declare all dependencies. - eloyra

2 Answers

5
votes

It works just fine because React 17x introduces the JSX Transform - importing React will not be needed anymore. JSX will get auto transformed into javascript.

More info: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

0
votes

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.