Chapter 5. JSX
You’ve already seen JSX in action in the previous chapters. You know it’s all about writing JavaScript expressions containing XML that looks very much like HTML. For example:
const
hi
=
<
h1
>
Hello
</
h1
>;
And you know you can always “interrupt the flow” of XML by including more JavaScript expressions wrapped in curly braces:
const
planet
=
'Earth'
;
const
hi
=
<
h1
>
Hello
people
of
<
em
>
{
planet
}
</
em
>!</
h1
>;
That’s true even if the expressions happen to be conditions, loops, or more JSX:
const
rock
=
3
;
const
planet
=
<
em
>
{
rock
===
3
?
'Earth'
:
'Some other place'
}
</
em
>;
const
hi
=
<
h1
>
Hello
people
of
{
planet
}
!</
h1
>;
In this chapter, you’ll to learn more about JSX and explore some features that may surprise and/or delight you.
Note
To see the examples above in action, load 05.01.hellojsx.html from the book’s repo. The file is also an illustration of how you can have several React applications on the same page.
A Couple Tools
To experiment and get familiar with the JSX transforms, you can play with the live editor at https://babeljs.io/repl (shown in Figure 5-1). Make sure you check the “Prettify” option for better readability of the result.
As you can see in Figure 5-2, the JSX transform is lightweight and simple: the JSX source of “Hello world!” from Chapter 1 becomes a series of calls to React.createElement()
, using ...
Get React: Up & Running, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.