JSX: The Secret Sauce Behind React's Success

bowen

Ivan Bowen

Posted on February 24, 2023

JSX: The Secret Sauce Behind React's Success

React is a popular JavaScript library for building user interfaces. It was created by Facebook and released to the public in 2013. Since then, it has gained widespread adoption in the tech industry and is used by many companies, big and small, to build web and mobile applications.

One of the reasons for React's popularity is its ability to create complex and dynamic user interfaces with ease. React uses a syntax called JSX (JavaScript XML) allowing developers to write HTML-like code within JavaScript, making it easier to reason about the structure and behavior of their applications.

In this article, we will delve into the details of JSX and explore how it makes React such a powerful tool for building dynamic and engaging user interfaces.

Pre-requisites

To follow along through this article you are required to have:

  • Basic knowledge of HTML
  • Knowledge in Javascript
  • Basic React skills

Introduction

JSX is a syntax extension to Javascript and is used with React to describe how the user interface should look like. This enables React to utilize declarative aspect of programmming. You might find the word declarative a bit complex but don't worry we are going to cover it in this article.
To understand the role of JSX in React we will take a look at how we create HTML elements in plain JavaScript then look at how they are created in React.
We will cover:

  • Imperative vs Declarative Programming
  • Creating HTML elements in Vanilla JavaScript
  • Creating HTML elements in React
  • Nesting in JSX

Imperative vs Declarative Programming

Suppose you wish for someone to prepare a cake for breakfast. You have two options:
Firstly, you can simply request the baker to bake, assuming they know how to do it, and omit giving any instructions on the baking process. Alternatively, you can still request the cake but also provide the baker with instructions on how to go about the baking process.

Imperative programming is a software development paradigm where functions are implicitly coded in every step required to solve a problem while declarative programming is a paradigm which utilizes abstraction of the control flow behind how a particular solution is achieved.
Declarative describes what you want to do not how you want to do it.

The idea about giving instructions on how something should be done explains the imperative aspect of programming while the other explains declarative aspect of programming.

Creating HTML elements in Vanilla JavaScript

Before we get into how JSX is used in React applications, we will first get to understand how it is done in pure JavaScript.

Create an index.html file and paste the code below and open it in your browser.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>
   <h1>The Document Object Model</h1>
   <h2>The createElement() Method</h2>
   <p>Create a p element and append it to the div with id "myDiv"</p>
   <div id="myDiv" style="padding: 16px; background-color: paleturquoise;">
      <h3>My Div</h3>
   </div>
   <script>
      // create HTML element
      const paragraph = document.createElement("p");
      paragraph.innerHTML = "Created a paragraph using JS."

      // append to the myDiv div
      document.getElementById("myDiv").appendChild(paragraph)
   </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

createElement creates the HTML element specified by the tagName which is its parameter.
appendChild on the other hand adds the node or rather element created to the end of the list of children of the specified parent ('myDiv' in our case) node.

If you understood the two programming paradigms above you will categorize this as an imperative programming because we are implicitly giving instructions on how it should be done.

Creating HTML elements in React

In React, JSX is a syntax extension recommended to describe how the user interface should look like.
To further understand how this happens, we are going to create a simple React application by pasting the code below on our terminal.

npx create-react-app jsx-demo
cd jsx-demo
npm start
Enter fullscreen mode Exit fullscreen mode

You can edit the src/App.js file by pasting the code below

import React from "react"

function App() {
  const h1Title = <h1 className="h1title">JSX in a nutshell</h1>
  return(
    h1Title
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

In JavaScript, we cannot assign HTML elements to values as shown above, however, in React, JSX gives us the power to do that.

Since almost everything in JavaScript is an object the h1Title is also an object and we can log it to see what it contains.
Just below the h1Title assignment you can add console.log(h1Title)

{
   type: 'h1',
   props: {
      className: 'h1title',
      children: 'JSX in a nutshell'
   }
}
Enter fullscreen mode Exit fullscreen mode

The above is a cleaner view of the result which you are seeing on the console after inspecting your application. This representation is what is known as a React Element which represents the final HTML output as a plain object.

Each node in the JSX is a plain object describing a component instance or a DOM node and its desired properties(props).

The two main attributes of the React Element is the type which defines the type of node and the props which is the properties a component receives.

Once the React Elements for all components are established , React converts it into actual HTML DOM elements.

Nesting in JSX

Additionally, nesting can be done in JSX just as it can be done in HTML. One key concern when nesting JSX nodes is to ensure that there always has to be a parent node.

Consider a bad JSX implementation:

const pageContent = 
   <h1 className="h1title">JSX in a nutshell</h1>
   <p>It's amazing how JSX works</p>
Enter fullscreen mode Exit fullscreen mode

To address the error which will be generated by the code above we can wrap it with a div as shown below:

const pageContent = 
   <div className="page-content">
      <h1 className="h1title">JSX in a nutshell</h1>
      <p>It's amazing how JSX works</p>
   </div>
Enter fullscreen mode Exit fullscreen mode

We can also console pageContent object and see what it contains.

{
   type: 'div',
   props: {
      children: [
         {
            type: 'h1',
            props: {
               className: 'h1title',
               children: 'JSX in a nutshell'
            }
         },
         {
            type: 'p',
            props: {
               children: 'It\'s amazing how JSX works'
            }
         },
      ]
      className: 'page-content',
   }
}
Enter fullscreen mode Exit fullscreen mode

children is an array of two objects each representing a specific JSX node. Thid array will grow depending on the number of children a parent node has.
The ability of React to convert these objects into HTML elements without us, programmers, to implicitly do it, make React declarative.

Conclusion

Many React developers, myself included, lack an understanding of JSX and its role in React. However, after reading this article, we gained a straightforward understanding of JSX and how it enhances React as a powerful library.

If you enjoyed reading this article, please leave a like!

💖 💪 🙅 🚩
bowen
Ivan Bowen

Posted on February 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JSX
beginners JSX

December 22, 2021