Published in February 04, 2021

ReactJS JSX

What is It and How Does It Work?

reactjsx-christina-morilloImage via pexels

Introduction

What makes ReactJS unique from other JavaScript front-end frameworks is that it builds a virtual DOM from the specified UI. The virtual DOM is a representation of the browser DOM and is made up of JavaScript objects.

There are two ways to create UI in React that becomes the browser DOM. These include: using vanilla JavaScript or JSX.

This post is about JSX. By the end of this article, you’d know what JSX is, how it works and why you’ll prefer using it (if you’re not doing so already) in your front-end application.

If you’re curious and you want to know what the virtual DOM is and how it works using JavaScript, then you should check out this post first.

Why JSX?

The idea behind JSX is to provide a way to couple the app UI and its logic together rather than separating the two into different files. React does this by adding the logic and UI as a unit in a single file called a “Component.”

JSX is an alternative to creating UIs with pure JavaScript objects. More on this later.

JSX is not required by ReactJS, but it serves as a visual aid, and it makes creating React elements easy.

What is JSX?

JSX stands for JavaScript Syntax Extension, and as the name vaguely suggests, it is an HTML-XML-like syntax extension to the JavaScript language. Although it may look like HTML or XML, it is not. It’s a syntactic way of representing JavaScript Objects that are responsible for building HTML UI tags.

JSX is used with React to build UI in JavaScript, and it produces React elements that are rendered as the browser DOM.

Below is an example of a JSX expression.

const headerTag = (<h1>I am a header tag </h1>);

In JSX, it is possible to create component tags that encapsulate the functionalities of other components. Such tags are different from HTML tags. HTML tags start with a lower case while React component tags are with an upper case. In HTML, tags have attributes, but can’t share attribute data with its nested children element. React component pass data to nested components via properties or the “props” attribute.

// HTML tag
const htmlTag = (<strong>Follow on Twitter</strong>);

// React component
const Connect = props => (<strong>{props.text}</strong>);

// Call "Connect" tag component and pass property
const reactComponent = (<Connect text="Follow on Twitter" />);
/*  Encapsulate components  */
const Platforms = props => (
  <Twitter text={props.text} twitter="IG" />
    <Instagram text={props.text} instagram="Twitter" />
    <Github text={props.text} github="GitHub" />
);

// parent component pass data to nested components
const parentComponent = (<Platforms text="Follow me on" />)

// Render Component
REACTDOM.render(
    parentComponent,
    document.getElementById("root")
)
NOTE:

It is not technically required to surround JSX in parenthesis (), Parenthesis is used to separate JSX from JavaScript and for spanning JSX spans in multiple lines.

How does it work?

JSX is converted to JavaScript under the hood using a pre-processor build tool before it is loaded into the browser.

Since React is mostly used with the modern version of JavaScript, based on the ECMAScript standard, it has to be converted to a backwards-compatible version so older browser engines can run the code. This is achieved through a transpiler. The most common transpiler tool used by JavaScript developers is a plugin called Babel.

You’ve seen the Why, What and How of ReactJS’ JSX, now let’s take a deeper dive into how you can use JSX in your application.

Writing Expression in JSX.

Curly braces are used to wrap valid JavaScript expressions in JSX. This can either be an expression of number operations or a function call.

// Variable expression
const guest = "John"
const greeting = <h1>Hello, {guest}!</h1>

ReactDOM.render(
    greeting,
    document.getElementById('root')
);

In the example below, the result of a function call is written into the h1 tag.

// Function call expression
function formatName(guest) {
    return guest.firstName + ' ' + guest.lastName;
}

const guest = {firstName: "John", LastName: 'Doe'}

const element = (
    <h1>Hello, {formatName(guest)}!</h1>
);

ReactDOM.render(
    element,
    document.getElementById('root')
);

Using JSX in Expression.

JSX can be assigned to variables, used in conditionals and loops; accepted as arguments and returned from function calls. This is because, after compilation, JSX becomes mare JavaScript objects.

function isUser(user) {
   if (user) {
       return <h1>hello, formatName(users)!</h1>;
   } else {
       return <h1>Hi! can I help you?</h1>;
   }
}

Attribute Expression in JSX.

To specify attribute in JSX, you should use quotes for string values and curly braces for expressions. Don’t use both for attribute values.

const element = (
  <div ClassName="container">"Hello World!" is getting old.</div>
    <img src={imageUrl}></img>
);
Warning:

Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

For example, class becomes className in JSX, and tabindex becomes tabIndex.

This is from the official _ReactJS documentaion_.

Specify Children element in JSX.

JSX can have multiple children elements. Empty tags should be closed with a /> at the end.

const user = {firstName: "John", LastName: 'Doe'}

// Multiple element
const elements = (
    <div>
        <h1>Hello {formatName(user.firstName)}</h1>
        <h2>Good to see you here.</h2>
        <h3>Have a greet stay!</h3>
    </div>
)

// Empty element
const element = <input type="email" name="user-email" value={state.userEmail} />;

No Injection attacks in JSX.

Malicious inputs are escaped in JSX. No input attack can be injected into the code, except explicitly set in the application. Cross-site scripting(XSS) attacks are prevented in JSX.

const title = response.inputAttack
// This is safe
const element = <h1>{title}</h1>

JSX is JavaScript Object.

Remember when I said JSX is an alternative to creating UI? Not only is that so, but it is a representation of JavaScript Object under the hood.

Let’s see why that is.

A transpiler compiles JSX down to React.createElement() calls. When you write JSX, the createElement() method is called from the React object class under the hood.

The two examples below are identical:

const element = (
  <h1 className="surprise">
    This is JSX!
  </h1>
);
const element = React.createElement(
  'h1',
  {className: 'surprise'},
  'This is JavaScript object!'
);

React.createElement() essentially creates a pure JavaScript object (key-value pair) like the one below:

// This structure is simplified
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};

The object above is called a “React element.” Those elements are what React uses to create and update the browser DOM.

Summary.

There you have it. JSX reduces the complexity of creating UIs and managing React application. The resemblance of JSX to HTML is part of what has made most front-end developers prefer ReactJS over other front-end frameworks.


Hi, my name is Romeo Peter. I'm a self-taught software developer and blogger --- I build web application, and automate business processes. I don't know it all, but what I do know, I manage to share for others to learn.

Follow me on Twitter. I share my thoughts there.

I'm available for work. Contact me to work on a project or work with you. I usually get back immediately.