Introduction to React Syntax: JSX (JavaScript XML)

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. In JavaScript XML (JSX), the term "XML" refers to Extensible Markup Language (XML), which is a structured language similar to HTML. JSX is not exactly XML, but it has a syntax inspired by XML. JSX allows developers to describe the UI structure using syntax similar to HTML, but it is transformed into JavaScript before being rendered by the browser.

1. JSX (JavaScript XML)

JSX allows writing HTML-like syntax inside JavaScript. It makes React code easier to read and write.

Example without JSX (Regular JavaScript)

const element = React.createElement("h1", null, "Hello, React!");

This is how you would write React elements without JSX.

        //App.js
        
        import React from "react";

        function App() {
          // Creating an element using React.createElement
          const element = React.createElement("h1", null, "Hello, React!");

          return element;
        }

        export default App;
        
        

Example with JSX

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

We can rewrite the above example using JSX, which makes it more readable and concise. This is the same as the previous example but using JSX.

         //App.js
        
            import React from "react";

            function App() {
              return <h1>Hello, React!</h1>;
            }
            
            export default App;
        
    

Key JSX Rules:

Understanding the "Only One Parent Element" Rule in JSX

In JSX (JavaScript XML), a component must return a single parent element. This is because JSX expressions must have one root element. If you try to return multiple elements without a parent container, you'll get an error.

Incorrect JSX (Will Cause an Error)

The following code won't work because it returns two sibling elements without a parent wrapper:
         
             function App() {
              return (
                <h1>Title</h1>
                <p>Paragraph</p>
              );
            }
            
            export default App;
         
    
❌ Error: JSX expressions must have one parent element

Using a <div> as a Parent Container

A simple & widely used approach is to wrap everything inside a <div>:
         
             function App() {
              return (
                <div>
                  <h1>Title</h1>
                  <p>Paragraph</p>
                </div>
              );
            }
            
            export default App;
         
    
✅ This works because now there is only one root element (<div>).

Using React Fragments (<>...</>)

Instead of using an unnecessary <div>, you can use React Fragments:
         
             function App() {
              return (
                <>
                  <h1>Title</h1>
                  <p>Paragraph</p>
                </>
              );
            }
            
            export default App;
         
    
✅ Fragments are invisible wrappers. Unlike a <div>, they don’t add an extra node to the DOM.

Named Fragments (<React.Fragment>...</React.Fragment>)

You can also use the full syntax instead of <>...</>:
        
        function App() {
          return (
            <React.Fragment>
              <h1>Title</h1>
              <p>Paragraph</p>
            </React.Fragment>
          );
        }
        
        export default App;
        
    
Normally, fragments (<>...</>) are used to avoid unnecessary <div> wrappers when returning multiple elements inside a component. However, there is one case where <>...</> cannot be used: When You Need to Add a key Property (e.g., Inside Lists). In React, when rendering lists dynamically, each element should have a unique key to help React efficiently update and re-render the UI.
        
            function App() {
                  const items = ["Item 1", "Item 2", "Item 3"];
                
                  return (
                    <>
                      {items.map((item, index) => (
                        <React.Fragment key={index}>
                          <h1>{item}</h1>
                          <p>Description of {item}</p>
                        </React.Fragment>
                      ))}
                    </>
                  );
            }    
        
    
This React function dynamically renders a list of items using JSX and <React.Fragment>.

Summary

Approach Pros Cons
<div>...</div> Simple & widely used Adds unnecessary divs to the HTML
<>...</> (Fragments) Prevents extra divs Cannot use key prop
<React.Fragment>...</React.Fragment> Supports key property Slightly longer syntax

Understanding Expressions Inside JSX:

JSX allows you to embed JavaScript expressions inside curly braces {} within your HTML-like code.
        
            import React from "react";

            function App() {
              const name = "Alice"; 
              return <h1>Hello, {name}!</h1>; 
            }
            
            export default App;
        
    

Understanding Attributes in JSX:

In JSX, attributes work similarly to HTML, but some differences exist:
        
        import React from "react";
        import "./App.css"; // Import the CSS file

        function App() {
          const imageUrl = "https://i.imgur.com/NUyttbnb.jpg";
          const inputPlaceholder = "Type here...";
          const isButtonDisabled = true;
          const textStyles = { color: "blue", fontSize: "18px", backgroundColor: "lightgray" };
        
          return (
            <div className="container">
              <h1 style={textStyles}>Hello, JSX Attributes!</h1>
              <img src={imageUrl} alt="Sample" width="300" />
              <br /> {/* a break line*/}
              <input type="text" placeholder={inputPlaceholder} />
              {"\u00A0".repeat(5)} {/* repeats the space 5 times */}
              <button disabled={isButtonDisabled}>Click Me</button>
            </div>
          );
        }
        
        export default App;
        
    

Summary Table: HTML vs. JSX

Feature HTML JSX
Class Attribute <div class="box"></div>
<div className="box"></div>
Inline Styles style="color: red;"
style={{"{ color: 'red' }"}}
Self-Closing Tags <img>   <br>   <input>
<img />   <br />   <input />
Comments <!-- This is an HTML comment -->
{/* This is a JSX comment */}

Installing Babel in Sublime for JSX

The Babel package in Sublime Text is a syntax highlighter that enables proper recognition of JavaScript XML (JSX) used in React.js. By default, Sublime does not recognize JSX syntax, so you must install the Babel package. It fixes issues where JSX is not recognized in Sublime Text.

1. Install Babel via Package Control

2. Set Babel as the Default Syntax for JSX