Update appNew update is available. Click here to update.

Introduction to JSX

Hari Sapna Nair
Last Updated: Mar 27, 2023

Introduction 

If you have ever seen any code in React, we run into some familiar-looking code blocks in the render method, which looks like HTML. Even though it may look like HTML, it is actually JSX or JavaScript XML, released with ES6 in 2015. JSX is popularly used in React to make the job of building an application much more effortless. Hence, it is good to have a brief introduction to JSX while learning React. 

Are you preparing for frontend interviews? Check out 15 Most Frequently Asked React JS Interview Questions now. 

This blog will give you an introduction to JSX, along with the features, advantages, and disadvantages of JSX.

Also See, Dropdown in React JS

Introduction to JSX

JSX(JavaScript XML) is simply a syntax extension of JavaScript. In React, JSX allows us to use JavaScript and its rich functionality coupled with HTML directly. JSX produces React elements which are rendered into rich user interfaces. 

JSX is used to write HTML-like code in the same file as you write JavaScript code. Here, unlike the traditional way of putting JavaScript into HTML, HTML is put into JavaScript.  

Let’s look at a simple JSX code in React.

const jsx = <h1 className="heading">JSX</h1>

Why use JSX?

The combination between a programming language and the markup language makes the applications robust and boosts their performance. It is faster than standard JavaScript as it performs optimizations while translating to regular JavaScript. 

JSX is basically a shorthand for calling React.createElement(), and it helps developers write effortlessly. JSX is also better suited for defining UI's when compared to a traditional templating solution.
 The JSX code is used in React in the following way:

class JSXComponent extends React.Component {

 render() {

   return <h1 className="heading">JSX</h1>;

 }

}

 

ReactDOM.render(<JSXDemo />,

 document.getElementById("root")

);

 

Here, JSX is returned from the JSXComponent and rendered on the screen using the ReactDOM.render method.

However, the browser does not understand the JSX because it's not valid JavaScript code. This is because an HTML tag is assigned to a variable that is not a string but a pure HTML code. So a tool like Babel, a JavaScript transcompiler, converts it to browser-understand JavaScript code. 

We can either use our babel configuration using  Webpack or use create-react-app, which internally uses Babel for the JSX to JavaScript conversion. 

When Babel executes the above JSX, it converts it to the following code:
 

class JSXComponent extends React.Component {

 render() {

     return React.createElement("h1", {className: "heading"}, "JSX");

 }

}

 

In the above code, we ask React to create an element with three parameters and then ask ReactDOM to render that element with the render() method. The three parameters are as follows:-

  1. The first parameter is the type of HTML element we want to create.
  2. The second parameter is the props which stand for properties. They are HTML attributes or arbitrary inputs within a component function that are passed as parameters. A prop object argument is passed with data, and it would return the modified React element in the DOM.
  3. The third parameter is the child element.
     
React.createElement(typepropschild);

 

This was the old way of writing React code. As you can observe, it was a tedious task to write the React.createElement every time, even for adding a simple h1 element. So React introduced the JSX, which made code easy to write and understand.  

When JSX is used with React, it is compiled into a single JavaScript file via Webpack. Since writing JSX requires less code than using React.createElement(), this will allow faster and more optimal performance. JSX does not need a JavaScript function to create HTML, so you can easily use the normal HTML code.

Features of JSX

Now that we have covered Introduction to JSX, let's discuss the various features of JSX. The features of JSX are as follows:-

  • JSX allows writing JavaScript expressions or React variables in curly braces.
  • The HTML code block is added inside the parenthesis.
  • JSX produces React elements.
  • JSX follows the rules of XML(Extensible Markup Language).
  • JSX expressions become regular JavaScript function calls after compilation.
  • JSX follows the camelcase notation for naming HTML attributes.

Expressions in JSX

With JSX, expressions are written inside curly braces { }. The expression can be a property, React variable, or any valid JavaScript expression. JSX executes the expression, and the result is returned. For example,

import React from "react";

 

const App = () => {

 const year = new Date().getFullYear();;

 const element = <h1>This is {year}</h1>;

 

 return (

     {element}

 );

};

 

export default App;

In the above example, the year and the h1 element are wrapped inside the curly brackets.

Nesting in JSX

If multiple lines are present in JSX, then it must be within a single parent element. If two h1 elements are required, they should be put in a parent element, like a div element. For example: 

import React from "react";

 

const App = () => {

 return (

   <div>

     <h1>Coding</h1>

     <h1>Ninjas</h1>

   </div>

 );

};

 

export default App;

In the above example, the h1 elements are wrapped inside the div element.

Note: If a tag is empty, you may close it immediately with />, like XML.

Alternatively, a "fragment" can be used to wrap multiple lines. Fragments groups a list of children elements without adding extra nodes to the DOM. A fragment will look like an empty HTML tag: <></>. For example, 

import React from "react";

 

const App = () => {

 return (

   <>

     <h1>Coding</h1>

     <h1>Ninjas</h1>

   </>

 );

};

 

export default App;

JSX Attributes

JSX uses a camelcase naming convention for attributes rather than the standard HTML naming convention. Custom attributes can also be used in JSX by using the data-prefix. In JSX, we can specify attribute values in the following ways:

  • String Literals: Values of attributes can be specified in double-quotes. For example,

import React from "react";

 

const App = () => {

 return (

   <div>

     <h1 className="heading">Hi</h1>

   </div>

 );

};

 

export default App;

 

  • Expressions: Values of attributes can be specified as expressions using curly braces. For example,
     

import React from "react";

 

const App = () => {

 const greeting = "Hi";

 return (

   <div>

     <h1 className="heading">{greeting}</h1>

   </div>

 );

};

 

export default App;

Props in JSX

The values assigned to the attributes are passed down as props (properties) to the React element. For example,

const student = (props=> (

   <div>

     <h1>Name: {props.name}</h1>

     <h1>Age: {props.age}</h1>

     <h1>Phone Number: {props.phoneNumber}</h1>

   </div>

 );

Prevention of Injection Attacks

React DOM escapes values embedded in JSX by converting them to a string before rendering them. This is done to ensure that nothing gets explicitly injected into the application.  

For example, we can embed user input as below,

 const input = response.potentiallyMaliciousInput;

 const element = <h1>{input}</h1>;

This helps to prevent Cross-site-scripting (XSS) attacks in the application.

To learn more about the security issues, check out the blog Best Security Practices For Node.Js Web Applications.

Check out Advantages of React JS here.

Advantages of JSX

The advantages of JSX are as follows:-

  • JSX makes it easier to develop React applications.
  • JSX converts HTML tags to React elements.
  • JSX is faster than regular JavaScript.
  • JSX allows you to add HTML elements in the DOM without using appendChild() or createElement() method.
  • JSX prevents Cross-Site Scripting (XSS) attacks or injection attacks.
  • JSX is type-safe, and errors are found at compilation time.

Disadvantages of JSX

The disadvantages of JSX are as follows:-

  • HTML code must be wrapped in a single parent element. Otherwise, an error occurs.
  • If HTML elements are not correctly closed, JSX will give an error.

Frequently Asked Questions

  1. What is Babel?
    Babel is a JavaScript transcompiler mainly used to convert ECMAScript code into a backward-compatible version of JavaScript that older JavaScript engines can run.
     
  2. Is it possible to write conditional statements in JSX?
    No, React does support conditional statements, but not inside JSX. To use conditional statements in JSX, we have to write the statements outside JSX. Or else we can use the ternary expression inside JSX.
     
  3. Why is className used in JSX instead of class.
    In HTML, we commonly use the class attribute. But in the JavaScript class keyword is a reserved word, and since JSX is rendered as JavaScript, we cannot use class in JSX.To solve this issue, instead of class, className is used.
     
  4. Can React work without JSX?
    Yes, React can work without JSX also. However, the task becomes tedious. 
     
  5. What is the difference between JSX and JavaScript?
    JavaScript is simply a scripting language that adds functionality to the website. JSX is an extension of JavaScript that makes the code easier to understand for the developers. 

Key Takeaways

This was a brief introduction to JSX. In this blog, we discussed JSX in-depth and the features, advantages, and disadvantages of JSX. 

Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? Attempt our Online Mock Test Series now! Also, check out our Guided Path to learn computer science fundamentals from scratch. 

We hope this introduction to JSX helped you understand JSX better. Feel free to let us know your thoughts in the comments section.

Was this article helpful ?
2 upvotes