Popular Searches
Popular Course Categories
Popular Courses

Introduction to JSX

Introduction to JSX

JSX in React

Introduction to JSX – Detailed Notes

JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code. JSX is commonly used in React applications to describe how user interfaces should look. It makes React components easier to read, write, maintain, and understand.

JSX looks similar to HTML, but it follows certain additional rules, such as closing all tags, using a single root element, and writing className instead of class for CSS classes.

Example:

function App() {
  return (
    <div>
      <h1>Welcome to React!</h1>
      <p>This is my first JSX example.</p>
    </div>
  );
}
export default App;

In this example, JSX is used inside the App JavaScript function to describe the user interface that React will render.

Learn more: Official React JSX Documentation


1. What Is JSX?

JSX is a syntax extension that allows developers to write markup-like expressions within JavaScript. React developers use JSX to describe elements such as headings, paragraphs, buttons, images, forms, and reusable components.

Although JSX resembles HTML, it is not HTML. Development tools transform JSX into JavaScript that React can process.

Example Without JSX

import { createElement } from "react";

function App() {
  return createElement(
    "h1",
    null,
    "Hello, React!"
  );
}
export default App;

Example With JSX

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

Both examples describe a heading, but JSX provides a more familiar and readable way to express the UI.


2. Why Is JSX Used in React?

JSX makes it easier to combine the visual structure of a component with the JavaScript logic responsible for displaying it.

  • Readable code: JSX looks similar to HTML, making the UI structure easy to understand.
  • Component-based development: JSX allows developers to create reusable UI components.
  • Dynamic content: JavaScript expressions can be included inside JSX using curly braces.
  • Easy maintenance: Related markup and rendering logic can be kept together.
  • Reusable interfaces: Custom React components can be included within JSX.
  • Developer support: Modern React development tools support JSX syntax, error reporting, and code transformation.

3. How Does JSX Work?

Browsers do not directly understand JSX syntax. A React development setup uses tools such as Vite and a JSX transform to convert JSX into JavaScript that can execute in the browser.

JSX Processing Flow

Developer writes JSX
        ↓
Build tool transforms JSX
        ↓
JavaScript is generated
        ↓
React processes the component
        ↓
React updates the browser DOM when needed
        ↓
User sees the interface

For example, the JSX expression

Hello

is transformed into JavaScript using the configured JSX runtime. The exact generated code depends on the project's compiler and configuration.

Important: JSX is a syntax extension, not a separate programming language and not a replacement for JavaScript. It works alongside JavaScript in React projects.


4. Basic Syntax of JSX

JSX uses familiar HTML-like tags inside JavaScript expressions. These tags can contain text, attributes, nested elements, JavaScript expressions, and React components.

Example

function Welcome() {
  return (
    <div>
      <h1>Welcome to My Website</h1>
      <p>Learn React with JSX.</p>
      <button>Get Started</button>
    </div>
  );
}
export default Welcome;

Explanation:

  • function Welcome() defines a React component.
  • return specifies the value returned by the function.
  • acts as the root element in this example.
  • displays the main heading.

  • displays a paragraph.


5. Rules of JSX

JSX follows rules that differ slightly from ordinary HTML. Understanding these rules helps prevent syntax errors.

Rule 1: Return a Single Root Element

A component must return one JSX element or one expression that represents the result. If you need to return multiple sibling elements, wrap them in a common parent or use a Fragment.

Incorrect:

function App() {
  return (
    <h1>Hello</h1>
    <p>Welcome to React</p>
  );
}

Correct using a div:

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <p>Welcome to React</p>
    </div>
  );
}

Correct using a Fragment:

function App() {
  return (
    <>
      <h1>Hello</h1>
      <p>Welcome to React</p>
    </>
  );
}

A Fragment groups elements without adding an extra DOM element.

Rule 2: Close All Tags

JSX requires every element to be closed. Elements without separate closing tags must use self-closing syntax.

Incorrect:

<img src="photo.jpg">
<br>

Correct:

<img src="photo.jpg" alt="Sample photo" />
<br />

Elements such as p, div, and li should also have their closing tags.

Rule 3: Use className Instead of class

In JSX, use className to assign a CSS class to an HTML element.

HTML:

<h1 class="title">Hello</h1>

JSX:

<h1 className="title">Hello</h1>

Rule 4: Use camelCase for Most DOM Event and Property Names

Many JSX DOM properties use camelCase rather than the lowercase or hyphenated forms commonly seen in HTML.

<button onClick={handleClick}>Click Me</button>
<label htmlFor="email">Email</label>
<div tabIndex={0}>Focusable element</div>

Some attributes, including aria-* and data-*, retain their hyphenated spelling.

Rule 5: Use Curly Braces for JavaScript Expressions

Curly braces allow you to include JavaScript expressions inside JSX.

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

The browser displays Hello, Rahul! because JSX evaluates the expression {name}.


6. Embedding JavaScript Expressions in JSX

JSX supports JavaScript expressions inside curly braces. This allows developers to display variable values, calculate results, access object properties, and call functions that return values.

Example 1: Display a Variable

function App() {
  const course = "React JS";
  return <h2>Course: {course}</h2>;
}
export default App;

Output: Course: React JS

Example 2: Perform a Calculation

function App() {
  const a = 10;
  const b = 20;
  return <p>Total: {a + b}</p>;
}
export default App;

Output: Total: 30

Example 3: Access an Object Property

function App() {
  const student = {
    name: "Amit",
    course: "React JS"
  };
  return (
    <div>
      <h2>{student.name}</h2>
      <p>{student.course}</p>
    </div>
  );
}
export default App;

Output: Amit and React JS

Example 4: Call a Function

function getMessage() {
  return "Welcome to React!";
}
function App() {
  return <h2>{getMessage()}</h2>;
}
export default App;

Note: Curly braces in JSX accept JavaScript expressions, not arbitrary statements such as a standalone if statement or a for loop. Use conditional expressions, array methods, or move more complex logic into JavaScript before the return.


7. Using Variables and Dynamic Data in JSX

Dynamic data allows a React component to display values that may differ depending on the data available to it.

function Product() {
  const productName = "Laptop";
  const price = 55000;
  const available = true;
  return (
    <div>
      <h2>{productName}</h2>
      <p>Price: ₹{price}</p>
      <p>Available: {available ? "Yes" : "No"}</p>
    </div>
  );
}
export default Product;

This example displays a product name, its price, and its availability. The conditional expression selects the appropriate text based on the value of available.

JavaScript booleans, null, and undefined generally do not display as text when placed directly in JSX. Use a conditional expression if you want to display a meaningful message.


8. Conditional Rendering in JSX

Conditional rendering means displaying different content depending on a condition. JSX supports common JavaScript conditional expressions such as the ternary operator and logical AND.

Example 1: Ternary Operator

function App() {
  const isLoggedIn = true;
  return (
    <div>
      {isLoggedIn
        ? <h2>Welcome Back!</h2>
        : <h2>Please Log In</h2>}
    </div>
  );
}
export default App;

Example 2: Logical AND Operator

function App() {
  const hasMessage = true;
  return (
    <div>
      {hasMessage && <p>You have a new message.</p>}
    </div>
  );
}
export default App;

The paragraph is rendered when hasMessage is true. Be careful when using && with numbers: for example, {0 &&

Hello

} renders the number 0. Use an explicit comparison such as count > 0 when necessary.


9. Rendering Lists in JSX

JSX can display collections of data by using JavaScript array methods such as map(). Each item rendered from a list should have a stable, unique key so React can track items between updates.

Example

function App() {
  const courses = ["HTML", "CSS", "JavaScript", "React"];
  return (
    <div>
      <h2>Available Courses</h2>
      <ul>
        {courses.map((course) => (
          <li key={course}>{course}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

Explanation:

  • courses stores an array of course names.
  • map() creates a list item for each course.
  • key={course} provides a stable key because the course names in this example are unique.

For data from a database or API, use a stable unique identifier, such as course.id, when available. Avoid using array indexes as keys when list items can be inserted, removed, or reordered.


10. Using Attributes in JSX

JSX elements can have attributes that configure their appearance and behaviour. Attribute values can be strings, JavaScript expressions, or other supported values, depending on the property.

String Attribute

<img src="logo.png" alt="Company logo" />

Dynamic Attribute

function App() {
  const imageUrl = "/images/profile.png";
  const imageDescription = "User profile";
  return (
    <img src={imageUrl} alt={imageDescription} />
  );
}
export default App;

Common JSX Attributes

HTML Attribute JSX Property Purpose
class className Assigns a CSS class.
for htmlFor Associates a label with a form control.
onclick onClick Handles click events.
tabindex tabIndex Controls keyboard focus order.
readonly readOnly Marks a supported form control as read-only.
maxlength maxLength Sets a maximum text length on supported controls.
style style Accepts a JavaScript object of inline styles.

Attribute naming and supported values depend on the specific HTML or SVG element. Consult the React documentation when an attribute behaves differently from standard HTML.


11. Styling Elements with JSX

React supports several ways to style JSX elements, including external CSS files, CSS modules, styling libraries, and inline style objects.

Method 1: External CSS

App.jsx

import "./App.css";

function App() {
  return <h1 className="heading">Hello React</h1>;
}
export default App;

App.css

.heading {
  color: blue;
  font-size: 32px;
}

Method 2: Inline Styles

In JSX, the style attribute accepts a JavaScript object. CSS properties that use hyphenated names generally use camelCase in this object.

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightgray",
    fontSize: "32px",
    padding: "10px"
  };
  return <h1 style={headingStyle}>Hello React</h1>;
}
export default App;

Important: Inline style values are usually strings or numbers, depending on the CSS property. Some numeric values represent pixel lengths, while others, such as opacity, are unitless.


12. Event Handling in JSX

JSX allows event handlers to be attached to elements using React event props such as onClick, onChange, and onSubmit. The event handler is usually a JavaScript function.

Example: Button Click

function App() {
  function handleClick() {
    alert("Button clicked!");
  }
  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}
export default App;

In this example, React calls handleClick when the user clicks the button.

Correct: onClick={handleClick}

Usually incorrect for this purpose: onClick={handleClick()}, because it calls the function during rendering rather than passing the function to be called when the event occurs.


13. JSX vs HTML

JSX is similar to HTML, but it is written within JavaScript and follows React-specific conventions.

Feature HTML JSX
Purpose Describes document structure. Describes UI within JavaScript expressions.
CSS class class="box" className="box"
Label association for="email" htmlFor="email"
Closing tags Some HTML elements may omit closing tags. Elements must be explicitly closed.
Multiple siblings Can appear together in an HTML document. Must be returned as one expression, usually wrapped in a parent or Fragment.
Dynamic expressions Usually require JavaScript in a separate context or framework. Can be embedded using curly braces.
Event handlers HTML has event attributes and browser event APIs. React commonly uses props such as onClick with function values.
Processing Browsers parse HTML. JSX is transformed into JavaScript by the development/build toolchain.

14. JSX vs JavaScript

JSX JavaScript
Provides HTML-like syntax for describing UI. Provides programming features such as variables, functions, loops, and conditions.
Commonly used inside React components. Can be used with or without React.
Requires transformation in typical browser-based React setups. Modern browsers execute JavaScript directly, subject to browser support and any build process.
Supports embedded JavaScript expressions. Provides the expressions and logic that JSX can use.

15. Common JSX Errors and Their Solutions

Error Reason Solution
Adjacent JSX elements must be wrapped. Multiple sibling elements were returned without a common wrapper. Wrap them in a parent element or Fragment.
Expected corresponding closing tag. An element was not closed correctly. Close the element or use self-closing syntax where appropriate.
class warning or issue. The HTML attribute was used instead of the JSX property. Use className for React DOM elements.
Unexpected text or value. A JavaScript value may be missing curly braces or a condition may be incorrect. Inspect the JSX expression and verify the data type and value.
List key warning. Elements generated from a list do not have suitable keys. Provide a stable, unique key for each list item.
Click handler runs immediately. The handler was called while rendering. Pass the function, for example onClick={handleClick}.
Inline style does not work. The style value may not be a JavaScript object or a property may be incorrectly named. Use an object with appropriate property names, such as backgroundColor.

16. Practical Example: Student Profile Card

This example combines JSX syntax, variables, attributes, expressions, and styling to create a simple student profile card.

function StudentCard() {
  const student = {
    name: "Priya Sharma",
    course: "React JS",
    duration: "3 Months",
    enrolled: true
  };

  const cardStyle = {
    border: "1px solid #ccc",
    padding: "16px",
    borderRadius: "8px",
    maxWidth: "320px"
  };

  return (
    <div style={cardStyle}>
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>Duration: {student.duration}</p>
      <p>
        Status: {student.enrolled ? "Enrolled" : "Not Enrolled"}
      </p>
    </div>
  );
}
export default StudentCard;

Concepts Used

  • JSX elements such as div, h2, and p.
  • JavaScript object properties displayed through curly braces.
  • Conditional rendering with the ternary operator.
  • Inline styling with a JavaScript object.
  • A reusable React function component.

Practice Tasks

  1. Change the student's name and course.
  2. Add a student ID to the object and display it.
  3. Display a different status when enrolled is false.
  4. Add a button with an onClick handler.
  5. Move the CSS styles into a separate stylesheet.

17. Best Practices for Writing JSX

  • Keep JSX readable by formatting nested elements consistently.
  • Use meaningful names for components and variables.
  • Start custom React component names with a capital letter.
  • Use lowercase names for built-in HTML elements.
  • Use className instead of class for CSS classes.
  • Close all elements correctly.
  • Use a Fragment when you need to group sibling elements without an extra DOM node.
  • Use curly braces to embed JavaScript expressions.
  • Use stable keys when rendering lists.
  • Keep complex calculations and business logic outside deeply nested JSX where practical.
  • Use semantic HTML elements and meaningful image alternative text.
  • Read compiler and browser console messages when debugging JSX errors.

18. Frequently Asked Interview Questions on JSX

Q1. What is JSX?

JSX is a JavaScript syntax extension that allows developers to write HTML-like markup within JavaScript code, commonly for React components.

Q2. Is JSX mandatory in React?

No. React can be used without JSX, but JSX is widely used because it makes UI code easier to read and write.

Q3. Is JSX the same as HTML?

No. JSX resembles HTML but is written within JavaScript expressions, follows stricter syntax rules, and uses some different property names.

Q4. Why do we use className instead of class?

React uses className as the DOM property for assigning CSS classes in JSX.

Q5. Why must JSX elements be closed?

JSX requires elements to have explicit closing tags or self-closing syntax so the markup structure is unambiguous.

Q6. What are curly braces used for in JSX?

Curly braces allow JavaScript expressions, such as variables, calculations, and function calls that return values, to be embedded in JSX.

Q7. What is a React Fragment?

A Fragment groups multiple JSX elements without adding an extra DOM element. It can be written as <>... or with the explicit Fragment component.

Q8. Can we use conditions in JSX?

Yes. Conditions can be expressed using a ternary operator, logical AND, or variables calculated before the return statement.

Q9. How are lists rendered in JSX?

Lists are commonly rendered with JavaScript's map() method, and each resulting element should have an appropriate stable key.

Q10. Does a browser understand JSX directly?

Browsers do not directly process JSX syntax. A build tool or compatible transformation process converts JSX into JavaScript.

Q11. Can JSX contain JavaScript objects?

Yes. JavaScript object properties can be accessed through expressions, and objects can be used for supported properties such as inline styles.

Q12. What is the difference between JSX and a React component?

JSX is a syntax extension used to describe UI. A React component is a reusable unit of UI that can return JSX or another supported React node.


19. Quick Revision Checklist

  • Understand the definition and purpose of JSX.
  • Know how JSX is transformed into JavaScript.
  • Write JSX inside a React component.
  • Return one root element or use a Fragment.
  • Close every JSX tag.
  • Use className and camelCase property names where required.
  • Embed variables and expressions using curly braces.
  • Render conditional content and lists.
  • Use event handlers correctly.
  • Recognize and fix common JSX errors.

20. Conclusion

JSX is an important concept in React development because it provides a clear and convenient way to describe user interfaces using JavaScript and HTML-like markup. By understanding JSX syntax, root elements, Fragments, attributes, curly braces, conditional rendering, lists, and event handlers, developers can create readable and reusable React components.

Practice writing small JSX components before moving on to advanced topics such as props, state, Hooks, forms, API integration, and routing.

Explore React JS Training: JustAcademy React JS Training Course

Register for a Demo: Register for React JS Course Demo

Official Learning Resources: Writing Markup with JSX | Describing the UI in React

whatsapp