Introducing JSX — React JS
2 min readSep 23, 2022
- JSX stands for Javascript Exts / Javascript XML.
- JSX is a javascript Exterion Syntax used in React to easily use HTML and Javascript together and place them in the DOM without any createElement() or appendChild() methods.
- JSX converts HTML tags into react element.
You are not required to use JSX, but JSX makes it easier to write React applications.
=>with JSX
const myElement = <h1> Sahil </h1>;
const root = ReactDOM.create.Root (document.getElementByld (‘root’));
=>without ISX
const myElement = React.createElement{‘h1’, {}, ‘Sahil’};
const root = ReactDOM.createRoot(document.getElementById(‘root’));
Expressions in JSX
- JSX you can write expressions inside curly braces “ { } “.
- The expression can be a react variable, property, or any other valid JavaScript expression.
- JSX will execute the expression and return the result.
Example
const myElement = <h1> React is {5+6} time good </h1>;
Inserting a large Block of HTML
To write HTML on multiple lines, put the HTML inside parentheses:
Example
const myElement={
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
<li>Cherries</li>
</ul>
One top-level element
- The HTML code must be wrapped in one top-level element.
- JSX will throw an error if HTML misses a parent element.
So, you can use a <React.Fragment> or <div> to wrap multiple lines
Example
<React.Fragment>
<h1></h1>
<h2></h2>
<p></p>
</React.Fragment>
or we use React.Fragment simple like this <></>
<>
<h1></h1>
<h2></h2>
<p></p>
</>
and we also use parent div
<div>
<h1></h1>
<h2></h2>
<p></p>
</div>
Elements must be closed
JSX follow XML rules, Therefore HTML element must be properly closed.
Example
const myElement = <input type = ‘text’/>;
const myElement = <img src={userImage}/>;
Attributes follow camelCase property naming convention
Class => className
for => htmlFor
onclick =>onClick
tabindex =>tabIndex