JSX is not HTML in JavaScript
#EndOfArticle #JustKidding #PleaseReadOn
Like, npm
is not an acronym for node package manager
, JSX also has a misconception.
Leave a smile if you are today's year old if you have just learned
npm
is notnode package manager
JSX is not HTML inside JavaScript. JSX is an HTML-like syntax.
JSX is a flavour of JavaScript that looks a lot like HTML
If we go in a traditional way,
import React from 'react';
import ReactDOM from 'react-dom/client';
const myName = React.createElement("h1", {}, "Hello")
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(myName)
Here, The React.createElement gives you an Object, which resides inside a function with the name myName, which later gets rendered to the DOM.
The Datatype of JSX is always an Object
This might look neat but imagine when we have more elements.
const item1 = React.createElement('li', {key: 1}, 'Item 1');
const item2 = React.createElement('li', {key: 2}, 'Item 2');
const item3 = React.createElement('li', {key: 3}, 'Item 3');
const item4 = React.createElement('li', {key: 4}, 'Item 4');
const item5 = React.createElement('li', {key: 5}, 'Item 5');
const list = React.createElement('ul', {}, [item1, item2, item3, item4, item5]);
const div = React.createElement('div', {}, list);
ReactDOM.render(div, document.getElementById('root'));
When it needs this much effort to nest few list items inside a div to render, on a large scale application where we have a complicated nested DOM tree, it is highly impossible to use this way.
And hence the Facebook Developers came up with JSX.
// Using React.createElement:
const element = React.createElement('h1', {className: 'greet'}, 'Hello, World!');
// Using JSX:
const element = <h1 className="greet">Hello, World!</h1>;
The codes written in JSX are concise, less verbose, and more readable.
JSX is not natively supported by JavaScript and must be transformed into JavaScript before it can be executed by the browser. This is typically done using a build tool such as Babel, which is a popular tool for compiling modern JavaScript code into code that can run in older browsers.