DEV Community

Cover image for What Is JSX?
Sontus Chandra Anik
Sontus Chandra Anik

Posted on

What Is JSX?

JSX is a React-specific XML/HTML-like syntax that extends ECMAScript to allow for the coexistence of XML/HTML-like text and JavaScript/React code. Preprocessors (i.e., transpilers like Babel) will employ this syntax to convert HTML-like content present in JavaScript files into standard JavaScript objects that a JavaScript engine will parse.
JSX allows you to write compact HTML/XML-like structures (e.g., DOM-like tree structures) in the same file as JavaScript code, and Babel will later convert these expressions to JavaScript code. Instead of putting JavaScript into HTML as in the past, JSX allows us to put HTML into JavaScript.
By using JSX one can write the following JSX/JavaScript code:

var nav = (
    <ul id="nav">
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Clients</a></li>
      <li><a href="#">Contact Us</a></li>
    </ul>
);

Enter fullscreen mode Exit fullscreen mode

And Babel will transform it into this:

var nav = React.createElement(
   "ul",
   { id: "nav" },
   React.createElement(
      "li",
      null,
      React.createElement(
         "a",
         { href: "#" },
         "Home"
      )
   ),
   React.createElement(
      "li",
      null,
      React.createElement(
         "a",
         { href: "#" },
         "About"
      )
   ),
   React.createElement(
      "li",
      null,
      React.createElement(
         "a",
         { href: "#" },
         "Clients"
      )
   ),
   React.createElement(
      "li",
      null,
      React.createElement(
         "a",
         { href: "#" },
         "Contact Us"
      )
   )
);

Enter fullscreen mode Exit fullscreen mode

You can think of JSX as a shorthand for calling React.createElement().
The idea of mixing HTML and JavaScript in the same file can be a rather contentious topic. Ignore the debate. Use it if you find it helpful. If not, write the React code required to create React nodes. Your choice. My opinion is that JSX provides a concise and familiar syntax for defining a tree structure with attributes that does not require learning a templating language or leaving JavaScript. Both of which are can be a win when building large applications

Top comments (2)

Collapse
 
opeolluwa profile image
ADEOYE ADEFEMI OPEOLUWA

I've been thinking is it possible to use JSX standalone (probably with deno) in building JavaScript powered app.

No need for HTML. Js all the way 🤔

Collapse
 
donnatyler profile image
DonnaTyler

I want to know more about this topic here, please share more . mantra to get ex back