DEV Community

Daksh Kulshrestha
Daksh Kulshrestha

Posted on

Mysterious ways of JSX

I always wonder whenever I use React, why do I import React from react library whereas I never use it in my code?
A simple Hello World could be written the following way

function myComponent(){
return <p>Hello World</p>
}
Enter fullscreen mode Exit fullscreen mode

I don't see React variable anywhere and code runs perfectly fine without any error. And when I don't import it, it throws a load of errors on my terminal window. So what's up with it?

After learning JSX and it's ways, I found that since it isn't native Javascipt code, it has to be first complied into Javascript by come compiler such as Babel.

The same code above then changes to

function myComponent(){
React.createElement("p", null, "Hello World")
}
Enter fullscreen mode Exit fullscreen mode

And if we don't import it, React isn't in scope, the code can't run and importing it is a necessity.

But that's a lot of hassle if you are making many different components right?

Well React heard us and from React 17, there is no need to import React from the library since there is going to be a new helper which is going to be automatically injected at the time of compiling just like this

import {jsx as _jsx} from 'react/jsx-runtime';

function myComponent(){
 return _jsx("p", null, "Hello World")
}
Enter fullscreen mode Exit fullscreen mode

Now you know why do we import React. That's it for the post. Thanks for sticking till the end.

Top comments (0)