Skip to main content

About JSX

JSX

JSX (JavaScript XML) is neither a string nor HTML. It is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.

Why React uses JSX

The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page’s logic lived separately in JavaScript.

But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why in React, rendering logic and markup live together in the same place, known as components. JSX plays a crucial role in uniting these elements by binding together the logic and content.


The Rules of JSX

1. Return a single root element

  • To return multiple elements from a component, wrap them with a single parent tag. For example, you can use a <div>
<div>
<h1>Hedy Lamarr's Todos</h1>
<img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" class="photo" />
<ul>
<li>first item</li>
<li>second item</li>
</ul>
</div>
  • If you don’t want to add an extra <div> to your markup, you can write and instead.This empty tag is called a Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.
<>
<h1>Hedy Lamarr's Todos</h1>
<img src="https://i.imgur.com/yXOvdOSs.jpg" alt="Hedy Lamarr" class="photo" />
<ul>
<li>first item</li>
<li>second item</li>
</ul>
</>

2. Close all the tags

JSX requires tags to be explicitly closed: self-closing tags like <img> must become <img /> and wrapping tags like <li>oranges must be written as <li>oranges</li>.

3. camelCase all most of the things!

  • JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects.
  • But JavaScript has limitations on variable names. For example, their names can’t contain dashes or be reserved words like class.
  • This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of stroke-width you use strokeWidth. Since class is a reserved word, in React you write className instead.
info

For historical reasons, aria-* and data-* attributes are written as in HTML with dashes.