JSX stands for JavaScript XML. JSX allows us to write HTML in React and place them in the DOM ( Document Object Model ) without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements.
Why JSX?
React embraces the fact that rendering logic is inherently coupled with other UI logic, how events are handled, how states are changing over time and how data is prepared for display.
React separates concerns with loosely coupled units called ‘components’ instead of artificially separating technologies by putting markup and logic in separate files.
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.
Expressions in JSX
With JSX we can write expressions inside curly braces {}.
The expression can be a React variable, or property, or any other valid JavaScript expression. For example, 2 + 2
, user.firstName
, or formatName(user).
JSX will execute the expression and return the result.
Look at the following example:
After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.
This means that you can use JSX inside of if
statements and for
loops, assign it to variables, accept it as arguments, and return it from functions.
Specifying Attributes with JSX
We can use quotes to specify string literals as attributes:
We can use curly braces to embed a JavaScript expression in an attribute:
Specifying Children with JSX
If a tag is empty, we can close it immediately with />
, like XML
JSX tags may contain children:
JSX prevents injection attacks
It is safe to embed user input in JSX. This helps prevent XSS ( cross-site-scripting ) attacks.
JSX represents Objects
Babel compiles JSX down to React.createElement()
calls.
The following examples are identical.
These objects are called “React elements”. We can think of them as descriptions of what we want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.