JSX — Markup Inside JavaScript
JSX looks like HTML, so it is tempting to paste HTML straight in. Most of it works, and the parts that do not work fail in small, annoying ways. Learn the handful of differences once and you will stop tripping over them.
The rule
Braces open JavaScript; everything else is strict, camelCase HTML.
Braces let you drop any JavaScript expression into markup: a variable, a calculation, a function call.
const book = { title: 'The Hobbit', pages: 310, cover: '/hobbit.jpg' };
function BookCard() {
return (
<article className="book">
<h2>{book.title}</h2>
<p>{book.pages} pages, about {Math.round(book.pages / 30)} days</p>
<img src={book.cover} alt={book.title} />
</article>
);
}Only expressions fit in braces. An if statement or a for loop does not; you will meet the expression forms (? :, &&, map) in the Rendering section.
Strict means:
- One root element per return. Wrap siblings in a parent or an empty fragment,
<>...</>, which adds nothing to the page. - Every tag is closed:
<img />,<br />,<input />.
camelCase HTML means attributes use JavaScript property names:
class→className,for→htmlForonclick→onClick,tabindex→tabIndexstyletakes an object:style={{ fontSize: 18 }}. The outer braces open JavaScript; the inner braces are the object. Numbers mean pixels for most size properties.
Two exceptions keep their dashes: aria-* and data-* attributes, such as aria-label.
Comments inside markup go in braces too: {/* like this */}.