Search⌘ K
AI Features

JSX as an Important Building Block in React Development

Explore the basics of JSX and its essential role in React development. Learn how JSX blends JavaScript with HTML-like syntax to create dynamic user interfaces. Understand how JSX translates into React.createElement calls, and grasp the structure of elements, props, and children to build components effectively.

We'll cover the following...

JSX

Let’s talk about JSX. JSX makes up a large portion of the code written in most React components and thus a large amount of React in general.

We believe JSX is one reason the developer community has so widely and readily adopted React.

JSX

Note: Nowadays, even other frameworks or libraries like Vue.js offer the possibility to use JSX to supercharge their components.

At first glance, JSX does not look very different from HTML or XML. As in XML or in XHTML, every opening element also needs to have a matching closing element (</div>) or has to be self-closing (<img/>). In contrast to XML and XTHML though, JSX can include JavaScript expressions, which makes it extremely powerful.

JSX elements are transformed into nested React.createElement() calls at a later step in our build process. JSX uses the tree structure of elements created by React.

This all sounds much more complicated than it actually is though. Let’s look at an example with the following HTML snippet:

<div id="app">
  <p>A paragraph in JSX</p>
  <p>Another paragraph</p>
</div>

If we use this snippet of HTML in JSX, Babel will later transpile it into the following executable JavaScript:

React.createElement(
  'div',
  { id: 'app' },
  React.createElement('p', null, 'A paragraph in JSX'),
  React.createElement('p', null, 'Another paragraph')
);

Let’s go through the arguments passed to createElement() in the above snippet.

  1. The first argument for the createElement() call denotes the tag name of the DOM element’s string representation or another JSX element (in this case, this would only be a function reference).
  2. The second argument of the createElement() call is the props of an element. Props are comparable to HTML attributes but are much more flexible than regular HTML attributes. They are not limited to strings but can also include arrays, objects, or even other React components as their value.
  3. All other arguments are the “children” of the element. In our example above, the div contains two children: two paragraphs (<p>). These, in turn, do not have any other props though (null) and only contain a text string, A paragraph in JSX and Another paragraph as their children.

JSX will become second nature to you in no time, even though at this point it might seem slightly intimidating. After practicing, it will seem very similar to writing HTML markup. Understanding how JSX works under the hood is still important, particularly when learning slightly more complex structures in the future.