The 6 rules of JSX: a live cheatsheet

Explore the 6 rules of JSX with live examples that update as you type.

James K Nelson

Hi! I've been playing with JavaScript for over half my life, and am building Frontend Armory to help share what I've learned along the way!

Read more by James

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!"
  )

JSX is not a special way to embed HTML in JavaScript. All JSX does is replace a file’s <tags> with equivalent calls to React.createElement(), using 6 rules.

This cheatsheet demonstrates the 6 rules of JSX with live examples. Get a feel for them by playing with the examples below, and seeing how the compiled output changes. If you want to reset to the initial example, just click the “…” icon, then hit “reset”.

For a printable reference, see the PDF cheatsheet!

<tags> are elements #

JSX <tags> map to calls to React.createElement().

Use <lowercase /> tags when you need a DOM elements, and <Capitalized /> tags for component elements.

main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress

JSX children become child elements #

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.

main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress

Attributes are props #

  • Use "" quotes when your props are strings
  • Use {} braces when your props are literals or variables
  • And use bare attribute names to indicate a value of true.
main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress

{} interpolates children #

When a pair of {} braces is encountered within a JSX element, it’s value will be interpolated in as a child.

You can interpolate anything that can be passed as an element’s children, including text, elements, or even arrays

main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress

Empty <> tags #

A pair of empty <> and </> tags get’s turned into a React.Fragment element, i.e. an element that doesn’t map to DOM nodes.

Fragments are useful for returning multiple cells or list items from a component.

main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress

{...object} acts like Object.assign() #

Passing {...object} as an attribute will add all of the properties of the object as separate attributes. It’s a bit calling Object.assign() on the props that you’ll pass to createElement().

Combining JSX’s {...object} with destructuring assignment and rest parameters is a great way to pass through some of an element’s props to a child.

main.pretty.js
index.html
New
This file type is not compiled.
Build In Progress