Browse Tutorials
Getting Started with JSX

Getting Started with JSX

16 Mar 2024
Beginner
6.44K Views
14 min read

Getting Started With JSX: An Overview

JSX in React is the reason that makes developers grow to love the library due to its HTML-type syntax. React has been popular with developers for quite some time now with 108k stars on Github.

So, what is JSX anyway? Let's explore JSX in depth and JSX Concepts in this React Tutorial. And if you're feeling lost in the world of React, wasting time without progress? It's time for a change! Join our React JS certification Training, where we'll guide you on an exciting journey to master React efficiently and on schedule.

What is JSX in React

  • JavaScript XML (JSX) is an extension to the JavaScript language syntax. Similar in appearance to HTML, JSX provides a way to structure component rendering using syntax familiar to many developers. So means, this JSX is just simply a JavaScript expression that is taking the structure of XML to make it look like an HTML format inside JavaScript.
  • By using JSX syntax, we can write concise and similar to the HTML & XML structures in the same file as we write native JavaScript code along with all the desired expressions, then the Babel will transform those expressions into actual native JavaScript codebase. Instead of putting JavaScript into HTML markup, JSX allows us to put HTML into the JavaScript codebase effectively.
  • By default, JSX isn’t supported as an official syntax of JavaScript (but it is a way to use it for React development). So we need to make use of babel to transpile JSX syntax into plain native JavaScript using babel.

Read More: How to Start Your Dream Career with React Development

JSX Transpiler

JSX Transpiler

  • For the most part of using JSX in our react apps, we’re going to rely on transpilers. In case you’re wondering, transpiling stands for transform and compiling.
  • We’re going to rely on babel for the most part in transpiling our react apps.
  • This is how JSX is transpiled to convert the code in acceptable javascript syntax. This makes use of babel and webpack to assist us in transpiling our code completely.

JSX Transpilation

    const AddIngredient = ({ onAddIngredient, onChangeIngredientName }) => (
  <div className="row" style={{ paddingBottom: "15px" }}>
    <div className="col-md-12">
      <form onSubmit={onAddIngredient}>
        <input type="text" className="form-control" onChange={(e) => onChangeIngredientName(e.target.value)} />
      </form>
    </div>
  </div>
);    

As explained earlier, we make use of both webpack and babel to initiate the JSX transpilation. Webpack serves as our javascript bundler while babel serves as our transpiler and convert JSX to plain native javascript codebase. When we do that, here’s what our code would look like after being transpiled:

 import React from 'react';

const AddIngredient = ({ onAddIngredient, onChangeIngredientName }) => (
  React.createElement(
    'div',
    { className: 'row', style: { paddingBottom: "15px" } },
    React.createElement(
      'div',
      { className: 'col-md-12' },
      React.createElement(
        'form',
        { onSubmit: onAddIngredient },
        React.createElement('input', {
          type: 'text',
          className: 'form-control',
          onChange: (e) => onChangeIngredientName(e.target.value)
        })
      )
    )
  )
);

export default AddIngredient;    

Read More: Top 50 React Interview Question & Answers

JSX concepts

Elements

    const element = <h2>Hello World</h2>;    

JSX produces react “elements” which in turn becomes an HTML element in DOM.

Ex.

As you can see, an element fully resembles how HTML syntax is declared. So it’s safe to say that you can catch up pretty quickly in using JSX syntax.

Nested elements

We can also nest of the HTML elements similar to what we’re doing in regular HTML syntax as given below:

const nestedElements = <div>
    <h1>Hello World</h1>
    <h2>How are you?<span><i>I'm fine</>
</div>    

Attributes

Just like HTML, each element contains attributes that enhance the behavior, design, and provides additional information of a specific element where the attributes were applied. This is applied like so:

const element = <button
                        id="button1"
                        name="myButton"
                        style={{color:blue, background: green}}
                        onClick={(e) => alert("you clicked me")}
                    >
                        Click me!
                    </button>    

JavaScript Expressions

JSX is an expression too. What this means is JSX becomes a regular javascript expression call and evaluates javascript objects.

Meaning, you can still use your conventional javascript expressions such as using conditional statements like if-else, loops like for, while, do-while loops, and functions. JSX is just javascript after the transpilation so it would be easier to write the JavaScript along with HTML markup at the same time.

Let’s take a look at this example:

componentToRender(userLoggedIn) {
    if (userLoggedIn) {
        return <h1>Welcome user!</h1>;
    } else {
        return <h1>You must login first</h1>;
    }
}    

In this snippet, we make use of conditional statements to decide what elements should we render on the page. This is one powerful feature of jsx to take javascript expressions into account.

Comments

We can put comments in JSX syntax to put comments/suggestions or anything you would like to add in a comment. This is done by doing just like in this example:

<div>
    {/* todo: improve this simple starter app */}
    <div>React simple starter</div>
</div>    

Conditional Statements and Loops

Just like the JavaScript, we can use all the conditional statements and loops because JSX is still just javascript as we explained earlier in the topic.

So, let’s take a look at how we can use conditional and loops in JSX:

Conditional statements:

if (userLoggedIn) {
    return <h1>Welcome user!</h1>;
} else {
    return <h1>You must login first</h1>;
}    

Loops

render() {
    let divElements = {};
    for (let index = 0; index < 5; index++) {
        divElements += <div>{index}</div>;
    }
    return (
        <div>
            {divElements}
        </div>
    );
}    
Summary

The JSX syntax is quite useful while developing React applications and it is not a default feature or compulsory for any means, but it has the feasibility to use expression while working with HTML markups at the same time which makes it easy for usability.

In this article, we’ve learned what is JSX, how it’s transpiled, the concepts, and how it influences React ecosystem in its structure that has been loved by tons of developers. I hope you guys enjoyed reading my article. You can also consider doing our react certification from ScholarHat to upskill your career.

FAQs

Q1. What is JSX?

JSX is the short term for JavaScript XML. It is used to write HTML-like code within JavaScript to create React Components.

Q2. Is JSX required for React?

No, JSX is not a necessity for React but it is mostly preferred as it makes building user interfaces more simple and readable in React applications.

Q3. What is the difference of JS and JSX?

JavaScript is a programming language commonly used for web development. Whereas, JSX is an extension particularly made for React which is used to write HTML-like code within JavaScript.

Take our free react skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Sonny Recio (Front-end Engineer and Fullstack Web Developer)

Experienced developer with a five-year track record of commended performance in modular and object-oriented programming. Well-versed in all phases of the software development lifecycle, with a strong working knowledge of algorithms and data structures. Proven success in engineering customized solutions improving business processes, operations, and profitability as well as improving employees productivity through developing a user-friendly System.
Accept cookies & close this