JSX is just a tool that converts files like this:
let element =
<div className='test'>
Hello, world!
</div>
Into files like this:
let element =
React.createElement(
'div',
{ className: 'test' },
"Hello, world!"
)
Simple, right? All JSX does is replace a file’s <tags>
with equivalent calls to React.createElement()
. This reduces the amount of code you need to write, and allows editors to provide syntax highlighting for element trees. As a result, it’ll make you way more productive — but more importantly — you’ll just have a whole lot more fun.
So how does JSX do it? Actually, JSX itself doesn’t do anything. It’s just a language extension, so to use it you’ll need to compile your JSX files into JavaScript files.
As it happens, the editor in this course can handle the compilation for you. What’s more, it’ll even show you the compiled code if you click the Compile button at the bottom left. Let’s use this feature to take a look at the four most important rules of JSX.
I’ve only included the 4 most common rules in this list. You can see all 6 rules at:
<tags>
are elementsJSX <tags>
map to calls to React.createElement()
.
The children of a JSX tag map to the third and subsequent arguments of React.createElement()
, i.e. they become the element’s props.children
.
JSX children can be text, elements, or a mix of both.
props
""
quotes when your props
are strings{}
braces when your props
are literals or variablestrue
{}
interpolates childrenWhen a pair of {}
braces is encountered within a JSX element, it’s value will be interpolated in.
You can interpolate anything that can be passed as an element’s children, including text, elements, or even arrays — which we’ll cover in a few lessons time.
Throughout this course, I’ll be switching back and forth between JSX and raw createElement()
— just so you can see how they both work. For your own projects though, I highly recommend that you stick with JSX. Of course, this means that you’ll need a build system like Create React App, and that’s why we’ll cover it right after a quick exercise.