Popular Searches
Popular Course Categories
Popular Courses

Introduction to JSX

Introduction to JSX

JSX in React

Introduction to JSX in React

1. What is JSX?

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code. JSX is commonly used with React to describe how user interfaces should look and what content should appear on the screen.

Although JSX looks similar to HTML, it is not HTML. JSX is transformed into JavaScript by development tools such as Vite and its build tooling before the browser executes the application.

Example of JSX

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

Output: Hello, React!

In this example, the h1 element is written inside a JavaScript function using JSX syntax. React uses this description to render the heading in the user interface.


2. Why Do We Use JSX?

JSX makes React development easier because it allows developers to write UI markup alongside the JavaScript logic responsible for displaying it.

  • Readable code: JSX makes the structure of a user interface 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 stay together.
  • Reusable elements: Components can be combined to build larger interfaces.
  • Conditional rendering: Different UI elements can be displayed depending on application data.

Example

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

Output: Welcome to React, followed by Hello, Rahul!


3. JSX vs HTML

JSX resembles HTML, but some syntax rules and attribute names are different because JSX is written within JavaScript.

Feature HTML JSX
CSS class attribute class="container" className="container"
JavaScript content Usually added through scripts or templates {name}
Self-closing elements Some HTML elements do not require a closing slash <img />, <br />
Event attributes onclick onClick
Inline styles Usually use a CSS string Use a JavaScript object
Multiple root elements Can appear together in an HTML document Must be grouped into one returned JSX root

HTML Example

<div class="box">
  <h1>Hello World</h1>
</div>

Equivalent JSX Example

function App() {
  return (
    <div className="box">
      <h1>Hello World</h1>
    </div>
  );
}
export default App;

4. Basic Structure of JSX

JSX can contain HTML-like tags, attributes, text, JavaScript expressions and other React components. A component commonly returns JSX from a function.

function Welcome() {
  return (
    <div>
      <h1>Welcome</h1>
      <p>Learn React with JSX.</p>
    </div>
  );
}
export default Welcome;

In this example:

  • function Welcome() defines a React component.
  • return specifies the JSX description returned by the component.
  • <div> groups the child elements.
  • <h1> displays a heading.
  • <p> displays a paragraph.
  • export default Welcome allows the component to be imported into another file.

5. Rules of JSX

Rule 1: Return a Single Root Element

A component must return one JSX root. When several elements need to be returned together, wrap them in a parent element or a React Fragment.

Incorrect example:

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

Correct example using a div:

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

Rule 2: Close Every Tag

JSX requires every element to be properly closed. Self-closing elements must end with a slash.

function App() {
  return (
    <div>
      <h1>My Website</h1>
      <img src="/logo.png" alt="Website logo" />
      <br />
      <p>Welcome to my website.</p>
    </div>
  );
}

Rule 3: Use className Instead of class

Because JSX uses JavaScript syntax, the HTML class attribute is written as className.

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

Rule 4: Use camelCase for Most JSX Event and DOM Properties

Many JSX attributes use camelCase rather than the lowercase naming commonly seen in HTML.

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

Notice that onClick uses a capital C and receives a function reference.

Rule 5: Use Curly Braces for JavaScript Expressions

Curly braces allow you to use JavaScript expressions inside JSX attributes or between JSX tags.

function App() {
  const age = 22;
  return (
    <div>
      <h1>My Profile</h1>
      <p>Age: {age}</p>
      <p>Next year: {age + 1}</p>
    </div>
  );
}

6. Using JavaScript Expressions in JSX

JSX allows JavaScript expressions inside curly braces. An expression produces a value, such as a string, number, calculation result or function call.

Example 1: Display a Variable

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

Example 2: Perform a Calculation

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

Example 3: Call a Function

function App() {
  function getMessage() {
    return "Welcome to React";
  }
  return <h1>{getMessage()}</h1>;
}

Important: Curly braces accept JavaScript expressions, not arbitrary statements such as a traditional if statement or a for loop. For conditions, use a ternary expression, logical AND, or prepare the value before the return statement.


7. Using Variables in JSX

Variables make it possible to display data that may change depending on the application.

function App() {
  const course = "React JS";
  const duration = "3 Months";
  return (
    <div>
      <h1>Course Details</h1>
      <p>Course: {course}</p>
      <p>Duration: {duration}</p>
    </div>
  );
}
export default App;

Variables can store names, prices, course details, scores and other information that should appear in the interface.


8. JSX Attributes

Attributes provide additional information to JSX elements. They can set image sources, alternative text, CSS classes, links and other properties.

function App() {
  return (
    <div>
      <img
        src="/react-logo.png"
        alt="React logo"
        className="react-logo"
      />
      <a href="https://react.dev">Learn React</a>
    </div>
  );
}

Common JSX attributes include:

  • className — assigns a CSS class.
  • id — assigns an element identifier.
  • src — specifies an image source.
  • alt — provides alternative text for an image.
  • href — specifies a link destination.
  • onClick — assigns a click event handler.
  • style — accepts an inline style object.

9. Inline Styling in JSX

In JSX, the style attribute accepts a JavaScript object rather than a CSS string. CSS properties are generally written in camelCase, and string values are used when appropriate.

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightyellow",
    fontSize: "28px",
    textAlign: "center"
  };
  return (
    <h1 style={headingStyle}>
      Welcome to React
    </h1>
  );
}
export default App;

Explanation: The object contains CSS properties and their values. The expression inside style={headingStyle} passes the object to the element.


10. Conditional Rendering with JSX

Conditional rendering means displaying different UI content depending on a condition.

Using a Ternary Operator

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

Using Logical AND

function App() {
  const hasNotifications = true;
  return (
    <div>
      <h1>Dashboard</h1>
      {hasNotifications && <p>You have new notifications.</p>}
    </div>
  );
}

Use a ternary operator when you need one of two alternatives. Use logical AND when an element should appear only when a condition is true.


11. Rendering Lists in JSX

React commonly renders lists by using JavaScript's map() method. Each item rendered from a list should have a stable, unique key whenever possible.

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

Explanation: The map() method creates an array of JSX list items. The key helps React identify items when a list changes.


12. Using JSX with React Components

JSX allows one React component to be used inside another. Component names must begin with a capital letter, while built-in HTML tags are written in lowercase.

function Header() {
  return <h1>My React Website</h1>;
}
function Footer() {
  return <p>Copyright 2026</p>;
}
function App() {
  return (
    <div>
      <Header />
      <p>Welcome to the home page.</p>
      <Footer />
    </div>
  );
}
export default App;

Here, the App component reuses Header and Footer as JSX elements. This approach helps organize an application into smaller and reusable parts.


13. What Is a React Fragment?

A React Fragment groups multiple JSX elements without adding an extra DOM element. The shorthand syntax is an opening <> and closing </>.

function App() {
  return (
    <>
      <h1>About Us</h1>
      <p>We build modern web applications.</p>
    </>
  );
}

Fragments are useful when several elements need a common JSX root but an additional div would be unnecessary.


14. How JSX Works

JSX is not directly understood by browsers as JavaScript syntax. A compatible build tool transforms JSX into JavaScript that React can use.

  1. The developer writes JSX in a React component.
  2. A build tool processes and transforms the JSX syntax.
  3. The transformed JavaScript creates React element descriptions.
  4. React uses those descriptions to render and update the user interface.
  5. When relevant data changes, React can update the affected parts of the UI.

Modern React tooling commonly uses Vite with a React plugin or another compatible compiler to support JSX.


15. Common JSX Errors and Solutions

Error Reason Solution
Adjacent JSX elements Multiple root elements are returned without a wrapper. Wrap them in a div or Fragment.
Missing closing tag An element is not properly closed. Close the element or use self-closing syntax.
Using class HTML attribute syntax was used for a CSS class. Use className.
Incorrect event naming An event uses lowercase HTML-style naming. Use JSX event names such as onClick.
Missing list key Mapped list items have no stable key. Add a unique key to each item.
Invalid inline style A CSS string was passed directly to the JSX style attribute. Pass a JavaScript style object.
JavaScript variable not defined A referenced variable does not exist in scope. Declare the variable or correct its name.

16. Best Practices for Writing JSX

  • Keep components small, focused and reusable.
  • Use meaningful component and variable names.
  • Close all JSX tags properly.
  • Use a single root element or a Fragment when returning multiple elements.
  • Use className for CSS classes.
  • Use curly braces for JavaScript expressions.
  • Use stable keys when rendering lists.
  • Use accessible attributes such as meaningful image alt text.
  • Keep formatting consistent and indent nested JSX clearly.
  • Read compiler and browser console errors carefully when debugging.

17. Practical Example: Student Profile Card

This example combines JSX, variables, attributes, expressions and CSS classes to display a simple student profile.

function StudentProfile() {
  const student = {
    name: "Priya Sharma",
    course: "React JS",
    duration: "3 Months"
  };
  return (
    <div className="student-card">
      <h1>Student Profile</h1>
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>Duration: {student.duration}</p>
      <button onClick={() => alert("Profile viewed!")}>
        View Profile
      </button>
    </div>
  );
}
export default StudentProfile;

CSS Example

.student-card {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  font-family: Arial, sans-serif;
}
.student-card h1 {
  color: #2563eb;
}
.student-card button {
  padding: 10px 16px;
  cursor: pointer;
}

Learning outcome: This example demonstrates how JSX combines structured markup with JavaScript data and event handling to create a reusable UI component.


18. Frequently Asked Interview Questions

Q1. What is JSX?

JSX is a JavaScript syntax extension that lets developers write HTML-like markup inside JavaScript code, commonly for React user interfaces.

Q2. Is JSX the same as HTML?

No. JSX resembles HTML but follows JavaScript-oriented rules, including using className, camelCase DOM properties and explicit tag closing.

Q3. Is JSX compulsory in React?

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

Q4. Why do we use curly braces in JSX?

Curly braces allow JavaScript expressions to be evaluated within JSX markup or attribute values.

Q5. Why must JSX have one root element?

A component's JSX return must describe one root value. Multiple sibling elements can be grouped inside a parent element or a Fragment.

Q6. What is className in JSX?

className is the JSX property used to assign a CSS class to an element.

Q7. What is a Fragment?

A Fragment groups multiple JSX elements without creating an additional DOM element.

Q8. What is the purpose of a key in JSX lists?

A key helps React identify list items between renders so it can handle insertions, removals and reordering correctly.

Q9. Can we write JavaScript inside JSX?

Yes. JavaScript expressions can be placed inside curly braces, for example {2 + 3} or {student.name}.

Q10. How is JSX transformed?

A JSX-compatible compiler or build tool transforms JSX syntax into JavaScript that React can process.


19. Practice Exercises

  1. Create a component that displays your name and city.
  2. Create a heading and paragraph inside a single JSX root.
  3. Display the result of adding two numbers using curly braces.
  4. Create an image with src, alt and className attributes.
  5. Create a button that displays an alert when clicked.
  6. Render a list of five programming languages using map() and unique keys.
  7. Use a ternary operator to show whether a student has passed or failed.
  8. Create a profile component that receives a name and course through props.

20. Quick Revision Checklist

  • Understand the meaning of JSX.
  • Know why JSX is commonly used with React.
  • Understand the differences between JSX and HTML.
  • Know how to use curly braces for JavaScript expressions.
  • Remember to close tags and return one root element.
  • Know the purpose of className and camelCase event properties.
  • Understand JSX attributes, inline styling and conditional rendering.
  • Know how to render lists with stable keys.
  • Understand how JSX is transformed by build tools.
  • Practice creating small React components using JSX.

21. Conclusion

JSX is one of the foundational concepts in React development. It allows developers to describe user interfaces with readable, HTML-like syntax inside JavaScript. By learning JSX rules, expressions, attributes, fragments, conditional rendering and lists, beginners can start building structured and reusable React components.

22. Learn React JS with JustAcademy

Explore the React JS Training Course to strengthen your understanding of JSX, components and modern React application development.

JustAcademy React JS Training Course

Register for a demo session to learn more about the course and its training approach.

Register for React JS Course Demo

23. Official React Documentation

For additional explanations and examples, refer to the official React guide:

React Official Documentation: Writing Markup with JSX

Previous Next
whatsapp