JSX Simplified: A Primer on Essential Concepts

JSX Simplified: A Primer on Essential Concepts

Table of contents

Background

Welcome back to the React Odyssey Series! In our first blog, "The ABCs of React: An Introduction," we took our first steps into the fascinating world of React. We talked about the core concepts and principles that make React a powerful and popular JavaScript library for building user interfaces. If you haven't read that yet, it's a great place to start.

Today, we're diving deeper into React's magic potion – JSX. JSX stands for JavaScript XML, and it's the secret sauce that makes React components look so much like HTML. It's time to simplify JSX and explore its essential concepts all in one blog. Yep, all in one bloggggggggg!

Introduction

What is JSX?

Before we dive headfirst into JSX, let's understand what it is. JSX is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript files. This code is then transformed into regular JavaScript by a tool like Babel before being rendered in the browser.

Why JSX?

Well, it makes React code more readable and maintainable. It bridges the gap between HTML and JavaScript, allowing you to create UI components in a way that feels natural and intuitive. It is not mandatory to use JSX in React, but it makes the development process easier and more readable. Without JSX, we would have to use React.createElement() method to create React elements and nest them inside each other to form a tree structure. (Hot Take: Creating React Element with React.createElement() method can be tedious and error-prone, especially for complex components.)

The createElement() function accepts three parameters and returns a React element:

React.createElement(
  type,
  [props],
  [...children]
)

Let’s make a React component using JSX and see how it translates to regular JavaScript function calls.

JSX Code

import React from 'react'

  function App (){
    return (
      <div>
    <p>Todo List</p>
    <ul>
      <li>Nisarg</li>
      <li>Thakkar</li>
    </ul>
  </div>
  );
};

JavaScript Code

import React from 'react'

function App() {
  return React.createElement(
    "div",
    null,
    React.createElement("p", null, "Todo list"),
    React.createElement(
    "ul",
    null,
    React.createElement("li", null, "Nisarg"),
    React.createElement("li", null, "Thakkar")));
  }

This is also how you would write React without JSX. With a bit of nesting, we can see that it is beginning to get unreadable and ugly. Not only does it look difficult to code, but it also looks difficult to maintain. That’s where JSX comes in, combining the beauty of HTML and the power of JavaScript.

React.createElement() function in the example above would return an object like this:

{
    "type": "div",
    "key": null,
    "ref": null,
    "props": {
      "children": [
        {
          "type": "p",
          "key": null,
          "ref": null,
          "props": {
            "children": "Todo list"
          },
          "_owner": null
        },
        {
          "type": "ul",
          "key": null,
          "ref": null,
          "props": {
            "children": [
              {
                "type": "li",
                "props": {
                  "children": "Nisarg"
                },
              },
              {
                "type": "li",
                "props": {
                  "children": "Thakkar"
                },
              }
            ]
          },
          "_owner": null
        }
      ]
    },
    "_owner": null
}

These objects are known as React elements, but they are just plain JavaScript objects. They describe what you want to see on the screen. They represent HTML elements, and they do not live on the page (the “real” DOM)—they live on the virtual DOM. React reads these objects and uses them to create HTML elements on the virtual DOM, after which it gets synced with the real DOM.

Element Creation:

In JSX, you can create elements that represent parts of your user interface. These elements look like HTML tags but are JavaScript objects.

Here's a simple example:

const element = <h1>Hello, Nisarg!</h1>;

In this example, we've created a JSX element that represents an <h1> tag. In this case, we're inserting the string "Hello, Nisarg!" into our JSX element.

Nested Elements:

Just like in regular HTML, you can nest elements inside each other. JSX makes it easy to create complex UI structures. For instance:

const greeting = (
  <div>
    <h1>Hola, Amigo!</h1>
    <p>Welcome to the React Odyssey Series.</p>
  </div>
);

In this example, we've nested an <h1> element and a <p> element inside a <div> element. JSX keeps the structure clear and readable.

Props:

You can also use attributes in JSX, just like in HTML. These attributes are called props (short for properties) in React.

For example:

const link = <a href="https://www.nisargthakkar.me">Visit My Porfolio</a>;

In this case, href is a prop with the value https://www.nisargthakkar.me. Props allow you to pass data from a parent component to its children. We talked about a detailed section of props in a separate blog.

JSX Expressions:

JSX is not limited to static content you can embed JavaScript expressions within it. This enables dynamic rendering.

Consider this example:

const user = {
  name: "Nisarg Thakkar",
  age: 20
};

const greeting = <p>Hello, {user.name}! You are {user.age} years old.</p>;

In this code, we're using the {} syntax to embed JavaScript expressions inside our JSX. This results in a personalized greeting that depends on the user object's properties.

Conditional Rendering:

JSX makes it straightforward to conditionally render elements. For instance, you can use the ternary operator for simple conditions:

const isLoggedIn = true;

const loginStatus = (
  <div>
    {isLoggedIn ? <p>Welcome, user!</p> : <p>Please log in.</p>}
  </div>
);

Here, we're conditionally rendering a welcome message if the isLoggedIn variable is true and a login prompt if it's false.

Mapping Arrays:

When working with arrays of data, you can map over them to generate JSX elements dynamically.

Let's say you have an array of items:

const items = ["Apple", "Banana", "Cherry"];

const itemList = (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

The map function iterates through the items array and generates a list of <li> elements with the array values. Notice the key prop, which helps React identify each list item efficiently.

Class Names and Styling:

Adding CSS classes to JSX elements is a common task. In JSX, you can use the className prop instead of the class attribute used in HTML:

const button = <button className="btn-primary">Click Me</button>;

This is because class is a reserved keyword in JavaScript, so React uses className to avoid conflicts.

Event Handling:

Handling user interactions is essential in web development. JSX allows you to attach event handlers easily:

function handleClick() {
  alert("Button clicked!");
}

const button = <button onClick={handleClick}>Click Me</button>;

In this example, we've attached an onClick event to the button that triggers the handleClick function when the button is clicked.

Before we wrap here are the Important JSX Rules

  1. You can only return one top-level element from a given component. This is usually known as a parent element and is used to group the content. Remember, JavaScript is the backbone of React, and in JavaScript, a function can only return one value.

  2. Some elements in HTML do not have a closing tag. In React JSX, every tag, including those with no closing tags, must be closed. If you have an element that doesn’t have a closing tag, you have to add a slash at the end (e.g., <hr/>).

  3. A React component must be capitalized. Component names that do not begin with a capital letter are treated like built-in components, and it results in strings (“div”, “span”…). When the component name is capitalized, it is treated as an identifier instead of a string.

  4. To include JavaScript expressions in JSX, you need to wrap them in curly braces. Content between the opening and closing curly braces will be evaluated as JavaScript.

  5. The term “class” is a reserved keyword in JavaScript. In React, we must substitute className for class.

Conclusion:

In this blog post, we've delved into the world of JSX and understand why it is necessary to explore its essential concepts. JSX simplifies the process of building user interfaces in React, making your code more readable and maintainable.

Stay tuned for the next installment in the React Odyssey Series, where we'll explore more advanced React concepts and techniques. Happy coding!

Did you find this article valuable?

Support NISARG THAKKAR by becoming a sponsor. Any amount is appreciated!