REACT -
JSX
What is JSX?
JSX stands for JavaScript XML.
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in
React.
Coding JSX
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.
Expressions 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:
Inserting a Large Block of HTML
To write HTML on multiple lines, put the HTML inside parentheses:
One Top Level Element
The HTML code must be wrapped in ONE top level element.
So if you like to write two paragraphs, you must put them inside a parent element,
like a div element.
A fragment looks like an empty HTML tag:
<></>.
JSX will throw an error if the HTML
is not correct, or if the HTML
misses a parent element.
Alternatively, you can use a
"fragment" to wrap multiple lines.
This will prevent unnecessarily
adding extra nodes to the DOM.
Attribute class = className
The class attribute is a much used attribute in HTML, but since JSX is rendered as
JavaScript, and the class keyword is a reserved word in JavaScript, you are not
allowed to use it in JSX.
Use attribute className instead.
JSX solved this by using className instead. When JSX is rendered, it translates
className attributes into class attributes.
Conditions - if statements
React supports if statements, but not inside JSX.
To be able to use conditional statements in JSX, you should put the if statements
outside of the JSX, or you could use a ternary expression instead: