Using JSX
Last updated
Last updated
It is a syntax extension for JS. It was written to be used with React. A basic unit of JSX is called a JSX element.
This element looks exactly like HTML, expect that we find it in a JS file instead of a HTML file.
Syntax extension means that JSX is not valid JS. Web browsers can't read it. If a JS file contains JSX code, that file will need to be compiled.
Create an index.html
and index.js
file
When you run this, you will see an error in the console:
In order for JS to read it, we need to use Babel (a compiler for JS) which takes in next generation JS syntax and compiles (transforms) them into valid JS that your browser can understand.
Think of Babel as a translator which converts React JSX to JS.
We add Babel by making the following changes to your index.html
Now your code should work!
JSX elements are treated as JS expressions. They can go anywhere that JS expressions can go. This means that JSX elements can be saved in a variable, passed to a function, stored in an object, etc.
Example of JSX element in a variable:
Example of JSX element in an object:
JSX elements can have attributes similar to HTML elements. A JSX attribute written using HTML-like syntax:
A single JSX element can have many attributes:
Just like HTML, you can also nest JSX elements. But if it takes up more than one line, you will need to wrap the multi-line JSX expression in parentheses:
Nested JSX expressions can be saved as variables, passed to functions, just like non-nested JSX expressions:
Note: We use parentheses around multi-line JSX expressions to avoid JS automatic semicolon insertion which adds semicolons to terminate statements which we don't necessarily want that behaviour in a JSX expression.
A JSX expression must have exactly ONE outermost element. The first opening tag and the final closing tag of a JSX expression must belong to the same JSX element.
This code will not work:
We need to add an element outside like this:
To render a JSX expression means we are making it appear onscreen:
Output:
ReactDOM
is the name of a JS library. This library contains several React-specific methods.
ReactDOM.render()
renders the JSX. It takes a JSX expression, creates a corresponding tree of DOM nodes, and adds that tree to the DOM.
<h1>Hello world</h1>
is the argument being passed to ReactDOM.render().
document.getElementById('app')
acted as a container for ReactDOM.render()
's first argument.
ReactDOM.render()
first argument should evaluate to a JSX expression, which means it can also be a variable:
The compiling is handled by Babel, a JS compiler. It converts ECMAScript intro a backwards compatible version of JS in current and older browsers or environments.