React JSX
React's HTML-like markup language
Earlier, we had a brief look at JSX (JavaScript XML) and so we will now have a closer look at:
React without and with JSX
JSX tag naming conventions
JSX attribute naming conventions
mandatory self-closing tags
containing JSX with a single div or fragment
Such features make JSX a little different from HTML, while it gives us a more familiar way to build user interfaces with React:
React without JSX
Without JSX, we would have to type in lengthy and bracket-heavy JavaScript method calls like such:
...just to output an HTML tag like this:
In general:
the first argument contains the component (element's) name
the second argument contains the component's attribute
finally, zero or more arguments at the end contain the component's children (we'll see what this means at the end of this page)
React with JSX
With JSX, the cryptic JavaScript createElement
call becomes more similar to HTML:
JSX tag naming conventions
Unlike HTML tags, JSX tags can have almost any name with the following conventions:
first letter capitalized
single "worded" and camel-cased as such: "CamelCase"
JSX attribute naming conventions
As with tags, JSX allows a greater range of names for attributes with the following conventions:
first letter lowercase
single "worded" and camel-cased as such: "camelCase"
As an example:
Restrictions with certain words also do occur (due to JavaScript reserved keywords) so use:
className
instead ofclass
htmlFor
instead offor
Self-closing tags
Unlike HTML tags, all JSX tags must self-close, i.e. have either a closing tag, or a closing slash before the closing bracket of a JSX tag:
Encapsulation by a single tag
All JSX tags must have a "container" tag that encapsulates, or wraps around, JSX tags:
A newer kind of container tag is known as a "Fragment" and looks something like a tag with the name removed:
React without JSX - again!
As alluded from the above, we also call each child tag, a "child element" or, more commonly, a "child component".
Now, if we were to write the last snippet without JSX, it would look like this:
"Vanilla React" indeed looks a lot more error-prone than JSX...
Last updated