JSX

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.

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>
    ...
  </ul>
</div>

If you don’t want to add an extra <div> to your markup, you can write <> and </> instead:

<>
  <h1>Hedy Lamarr's Todos</h1>
  <img 
    src="https://i.imgur.com/yXOvdOSs.jpg" 
    alt="Hedy Lamarr" 
    class="photo"
  >
  <ul>
    ...
  </ul>
</>

This empty tag is called a Fragment. Fragments let you group things without leaving any trace in the browser HTML tree.

createElement with JSX

import React from 'react';
function App() {
  return React.createElement(
    'div',
    { className: 'container' },
    React.createElement('h1', {}, 'My App')
  );
}

export default App;

Result

<div id="root">
    <div class="container">
        <h1>My App</h1>
    </div>
</div>
Was this page helpful?