JSX in detail - BEHIND JAVA

JSX is an XML/HTML-like syntax used by React that extends ECMAScript so that XML/HTML-like text can co-exist with JavaScript/React code. The syntax is intended to be used by preprocessors (i.e., transpilers like Babel) to transform HTML-like text found in JavaScript files into standard JavaScript objects that a JavaScript engine will parse.

Basically, by using JSX you can write concise HTML/XML-like structures (e.g., DOM like tree structures) in the same file as you write JavaScript code, then Babel will transform these expressions into actual JavaScript code. Unlike the past, instead of putting JavaScript into HTML, JSX allows us to put HTML into JavaScript.

By using JSX one can write the following JSX/JavaScript code:

And Babel will transform it into this:

Regarding JSX, note the following set of points

  • Don't think of JSX as a template but instead as a special/alternative JS syntax that has to be compiled. I.e., JSX is simply converting XML-like markup into JavaScript.
  • The Babel tool is a subjective selection from the React team for transforming ES* code and JSX syntax to ES5 code. You can learn more about Babel at http://babeljs.io/ or by reading the Babel handbook.
  • Less technical people can still understand and modify the required parts. CSS developers and designers will find JSX more familiar than JavaScript alone. I.e., HTML markup looks like HTML markup.
  • You can leverage the full power of JavaScript in HTML and avoid learning or using a templating language. JSX is not a templating solution. It is a declarative syntax used to express a tree structure of UI components.
  • By adding a JSX transformation step you'll find errors in your HTML you might otherwise miss.
  • JSX promotes the idea of inline styles. Which can be a good thing.
  • JSX is a separate thing from React itself. JSX does not attempt to comply with any XML or HTML specifications. JSX is designed as an ECMAScript feature and the similarity to XML/HTML is only at the surface (i.e., it looks like XML/HTML so you can just write something familiar). A JSX specification is currently being drafted to by used by anyone as an a XML-like syntax extension to ECMAScript without any defined semantics.
  • In JSX, alone is valid while alone isn't. You have to close all tags, always.

No comments:

Post a Comment

Pages