Redwan
Redwan

Reputation: 107

How Jsx is valid javascript?

I use react and jsx. my question is how jsx is a valid js syntax? only way that I think it's maybe true, is that react compiles all the file and converts jsx(s) to valid js. like what C preprocessor does with macros. is it true? and if it is true, is it right that we consider react as js library? I think it is higher level of a library.

if No, who it is done?

Upvotes: 6

Views: 642

Answers (2)

DecPK
DecPK

Reputation: 25408

JSX is just syntactic sugar over function calls of React.createElement, It is transpiled by Babel.

As a developer you may not like the way how react elements are created, so React team gave the JSX syntax and It is very easy and you can co-relate with HTML.

No one is stopping you to useReact.createElement. But that will your code overbloated.

Just take a case where you've decided to use Raw React then you would end up as below.

const list =
  React.createElement('div', {},
    React.createElement('h1', {}, 'My favorite ice cream flavors'),
    React.createElement('ul', {},
      [
        React.createElement('li', { className: 'brown' }, 'Chocolate'),
        React.createElement('li', { className: 'white' }, 'Vanilla'),
        React.createElement('li', { className: 'yellow' }, 'Banana')
      ]
    )
  );

The above code will work as expected but It has some limitation:

  1. Not readable
  2. Not Maintainable

After using JSX syntax, you won't have these problems as you can see below using JSX.

<div>
  <h1>My favorite ice cream flavors</h1>
  <ul>
    <li className="brown">Chocolate</li>
    <li className="white">Vanilla</li>
    <li className="yellow">Banana</li>
  </ul>
</div>

You can see it on babeljs.io

If your component is

import "./styles.css";

export default function App() {
  return (
    <div>
      <h1>Hello word</h1>
      <h2>I'm learning React</h2>
    </div>
  );
}

then It will be transpiled to

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = App;

require("./styles.css");

function App() {
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("h1", null, "Hello word"), /*#__PURE__*/React.createElement("h2", null, "I'm learning React"));
}

Upvotes: 10

Ahmad Habib
Ahmad Habib

Reputation: 2384

JSX is not a valid JavaScript.

JSX is a look-alike of JavaScript. A compiler Babel converts the JSX code into meaningful JavaScript code. With a JSX compiler, you can transform JSX expressions to calls to React.createElement

JSX:

<p style={{color:'#000', background:'blue'}}>This is JSX</p>

Compiled JavaScript:

"use strict";

/*#__PURE__*/
React.createElement("p", {
  style: {
    color: '#000',
    background: 'blue'
  }
}, "This is JSX");

You can play along to see runtime compilation here

Upvotes: 4

Related Questions