React JSX
React's HTML-like markup language
Last updated
React's HTML-like markup language
Last updated
, 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:
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)
With JSX, the cryptic JavaScript createElement
call becomes more similar to HTML:
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"
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 of class
htmlFor
instead of for
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:
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:
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...
That looks like a mistake but it's not! It simply allows the developer not to come up with a new name for a container tag