DEV Community

Daksh Kulshrestha
Daksh Kulshrestha

Posted on

3 2

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay