JSX
JSX stands for JavaScript XML. JSX allows us to write HTML elements with JavaScript code. An HTML element has an opening and closing tags, content, and attribute in the opening tag. However, some HTML elements may not have content and a closing tag - they are self closing elements.
To create HTML elements in React we do not use the createElement()
instead we just use JSX elements. Therefore, JSX makes it easier to write and add HTML elements in React. JSX will be converted to JavaScript on browser using a transpiler - babel.js. Babel is a library which transpiles JSX to pure JavaScript and latest JavaScript to older version. See the JSX code below.
In conclusion with Babel this:
becomes this:
JSX is stricter than html.
If you write for example <br>
in HTML this becomes valid.
If you write the same in JSX, it will throw an error.
Therefore you have to close every element properly:
Expressions in JSX
If you work with JSX, you can use expressions to inject values into jsx code:
Expressions produce values. According to MDN an expression is:
Do not confuse it with statements which produce code statements, assignments and expressions.
Statements | Expressions |
---|---|
let a = 1 + 2 |
1 + 2 |
if (1 === 2) { return 3 } else { return 4 } |
1 === 2 ? 3 : 4 |
For example, you can also use the result of a function inside of jsx:
Example
Attributes in JSX
You can specify attributes in JSX:
Warning
Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.
For example, class becomes className in JSX, and tabindex becomes tabIndex.
Children in JSX
We discussed simple elements for now. But when HTML elements can have children, JSX elements can have them too:
Warning
Do not use nested elements without paranthesis.
This is a false example:
Warning
Note that you cannot use multiple elements as JSX:
You have to wrap multiple elements into an outer element.
This can be another html element or the 'empty' element <>...
For example:
Example
will result as HTML in the DOM as:
Example
will result als HTML in the DOM as:
Adding styles
If you want to add a style to a JSX element, you can use className
(instead of the html class
) or style
.
Please note, that style
will be overwritten by Babel so that you cannot use just a string, but you use an object: