JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()
and/or appendChild()
methods.
JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications. JSX is a syntax extension to JavaScript. It may remind you of a template language, but it comes with the full power of JavaScript.
React doesn’t require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages. React embraces the fact that rendering logic is inherently coupled with other UI logic: how events are handled, how the state changes over time, and how the data is prepared for display.
Expression in JSX
With JSX you can write expressions inside curly braces { }
. The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result.
const element = <h1>React is {5 + 5} times better with JSX</h1>;
Inserting a big block of HTML code
const listOfNames = (
<ul>
<li>John</li>
<li>Peter</li>
<li>Charlie</li>
</ul>
);
One top element
The HTML code must be wrapped in ONE top level element. So if you like to write two headers, you must put them inside a parent element, like a div
element
const listOfNames = (
<div>
<h1>John</h1>
<h1>Peter</h1>
</div>
);
Elements must be closed
JSX follows XML rules, and therefore HTML elements must be properly closed. Close empty elements with />
const myelement = <input type="text" />;
Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.
const profileImg = <img src={user.imgUrl}></img>;
If a tag is empty, you may close it immediately with />
, like XML:
const profileImg = <img src={user.imgUrl}/>;
JSX tags may contain children:
const message = ( <div> <h1>Hi there!</h1> <h2>Come have lunch with me.</h2> </div> );
Note that everything is converted to a string before being rendered.