DEV Community

Muhammad Medhat
Muhammad Medhat

Posted on

Why to write jsx syntax in a .js file

You can write JSX syntax in a JavaScript file because JSX is not a separate language, but rather a syntax extension to JavaScript. This means that under the hood, JSX is actually compiled into regular JavaScript code that the browser can understand.

When you write JSX in a JavaScript file, you need to use a transpiler like Babel to convert the JSX code into JavaScript code that the browser can understand. The transpiler takes your JSX code and compiles it into regular JavaScript code by transforming the JSX syntax into function calls that create React elements.

For example, this JSX code:

const element = <div>Hello, world!</div>;
Enter fullscreen mode Exit fullscreen mode

would be compiled by Babel into this JavaScript code:

const element = React.createElement("div", null, "Hello, world!");
Enter fullscreen mode Exit fullscreen mode

As you can see, the JSX code has been transformed into a call to React.createElement(), which creates a React element.

So, while you're technically writing JSX syntax in a JavaScript file, it's important to understand that this is just a shorthand for writing regular JavaScript code that creates React elements. And with the help of a transpiler like Babel, you can use the full power of JSX syntax in your React applications, while still writing code that runs in the browser.

Top comments (1)

Collapse
 
artydev profile image
artydev

You don t need JSX, Babel, to create UI in JS
Look at vanjs.org/