Popular Searches
Popular Course Categories
Popular Courses

JSX Syntax and Rules

JSX Syntax and Rules

JSX in React

JSX Syntax and Rules – Detailed Notes

JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code. In React, JSX is commonly used to describe the structure and appearance of user interfaces. It makes components easier to read, maintain, and develop.

Although JSX resembles HTML, it follows specific rules, such as returning a single root element, closing all tags, using className instead of class, and embedding JavaScript expressions using curly braces.

Official Documentation: React JSX Syntax and Rules


1. What Is JSX Syntax?

JSX syntax defines how HTML-like elements, attributes, expressions, and React components are written inside JavaScript. It allows developers to describe UI elements directly within a React component.

Example

function App() {
  return (
    <div>
      <h1>Welcome to React</h1>
      <p>Learning JSX Syntax and Rules.</p>
    </div>
  );
}
export default App;

Explanation:

  • function App() defines a React component.
  • return specifies the JSX that the component returns.
  • is the parent element.
  • displays the main heading.

  • displays paragraph text.

JSX is transformed into JavaScript by the project's build tools. Browsers do not directly process JSX syntax.


2. Why Are JSX Rules Important?

JSX rules help developers write valid, consistent, and readable React components. Incorrect syntax can cause compilation errors, warnings, or unexpected UI behaviour.

  • Correct structure: Ensures that elements are nested properly.
  • Readable code: Makes component markup easier to understand.
  • Fewer errors: Helps prevent invalid tags and incorrect attributes.
  • Dynamic interfaces: Allows JavaScript values to be displayed correctly.
  • Reusable components: Makes it easier to combine custom React components.

3. Rule 1: Return a Single Root Element

A React component must return a single JSX element or expression. If you want to return multiple sibling elements, wrap them inside a common parent element or a React Fragment.

Incorrect Example

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

Problem: The component returns two sibling elements without a common wrapper.

Correct Example Using a div

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

Correct Example Using a Fragment

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

What is a Fragment? A Fragment groups multiple JSX elements without adding an extra DOM element to the rendered page.


4. Rule 2: Close All JSX Tags

Unlike HTML, JSX requires every element to be explicitly closed. Elements that do not have separate closing tags must use self-closing syntax.

Incorrect Example

function App() {
  return (
    <div>
      <h1>Welcome
      <img src="logo.png">
    </div>
  );
}

Problem: The heading is not closed, and the image does not use self-closing syntax.

Correct Example

function App() {
  return (
    <div>
      <h1>Welcome</h1>
      <img src="logo.png" alt="Company logo" />
    </div>
  );
}
export default App;

Examples of Properly Closed Tags

<p>This is a paragraph.</p>
<button>Click Me</button>
<input type="text" />
<br />
<img src="photo.jpg" alt="Sample photo" />

Remember: Always close opening and self-closing tags correctly.


5. Rule 3: Use className Instead of class

In JSX, use className to assign a CSS class to an HTML element. The name differs from HTML's class attribute because JSX uses JavaScript property conventions.

HTML Example

<h1 class="heading">Hello React</h1>

JSX Example

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

CSS Example

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

The heading class applies the specified CSS styles to the heading.


6. Rule 4: Use camelCase for Most JSX Properties

Many HTML and SVG attributes use camelCase names when written as JSX properties. This is because JSX attributes become properties in the JavaScript representation of an element.

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.
maxlength maxLength Sets the maximum length for supported text controls.
readonly readOnly Marks a supported form control as read-only.
stroke-width strokeWidth Sets the width of an SVG stroke.

Example

function App() {
  return (
    <div className="container">
      <label htmlFor="username">Username</label>
      <input id="username" type="text" maxLength={20} />
      <button onClick={() => alert("Clicked!")}>
        Submit
      </button>
    </div>
  );
}
export default App;

Important exception: Attributes beginning with aria- and data- retain their hyphenated names, such as aria-label and data-testid.


7. Rule 5: Use Curly Braces for JavaScript Expressions

Curly braces {} allow JavaScript expressions to be included inside JSX. They are useful for displaying variables, calculating values, accessing object properties, and calling functions that return values.

Example 1: Display a Variable

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

Output: Hello, Rahul!

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: "Priya",
    course: "React JS"
  };
  return (
    <div>
      <h2>{student.name}</h2>
      <p>{student.course}</p>
    </div>
  );
}
export default App;

Example 4: Use a Function

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

Important: Curly braces inside JSX accept JavaScript expressions, not standalone statements such as an ordinary if statement or for loop. Use a conditional expression or prepare the value before returning JSX.


8. Rule 6: Use Quotes for String Attributes and Braces for Dynamic Values

JSX uses quotes for literal string values and curly braces for JavaScript expressions used as attribute values.

String Attribute

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

Dynamic Attribute

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

In the second example, JSX reads the values stored in the JavaScript variables.

Incorrect Dynamic Attribute

<img src="{imageUrl}" alt="Profile" />

Here, "{imageUrl}" is treated as a literal string rather than as the value of the variable.

Correct: src={imageUrl}


9. Rule 7: Use Correct Opening and Closing Tag Names

Every JSX element with an opening tag must have a matching closing tag with the same name. The nesting order must also be correct.

Incorrect Example

function App() {
  return (
    <div>
      <h1>Hello
    </div>
  );
}

Correct Example

function App() {
  return (
    <div>
      <h1>Hello</h1>
    </div>
  );
}
export default App;

Correct Nested Elements

<div>
  <section>
    <h2>About Us</h2>
    <p>Learn about our company.</p>
  </section>
</div>

Nested JSX elements should be properly indented to make the structure easier to understand.


10. Rule 8: Use Capital Letters for Custom React Components

React component names should start with an uppercase letter. Lowercase names are used for built-in HTML elements.

Example

function WelcomeMessage() {
  return <h2>Welcome to React</h2>;
}

function App() {
  return (
    <div>
      <WelcomeMessage />
    </div>
  );
}
export default App;

represents a custom React component, while

represents a built-in HTML element.

Incorrect Naming

function welcomeMessage() {
  return <h2>Welcome</h2>;
}

Using a lowercase component name can cause JSX to treat it as a built-in element instead of the intended custom component.


11. Rule 9: Use Parentheses for Multiline JSX

When a component returns JSX across multiple lines, wrap the JSX expression in parentheses for clarity and to avoid JavaScript automatic semicolon insertion problems after the return statement.

Recommended Syntax

function App() {
  return (
    <div>
      <h1>React Training</h1>
      <p>Learn JSX step by step.</p>
    </div>
  );
}
export default App;

Common Mistake

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

Problem: JavaScript may treat the line break after return as the end of the statement, causing the function to return undefined.

Correct: Put the JSX on the same line as return, or wrap the multiline expression in parentheses immediately after return.


12. Rule 10: Use Conditional Expressions Correctly

Conditional rendering displays different UI content based on a condition. You can use a ternary expression or logical AND operator inside JSX.

Example Using the Ternary Operator

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

Example Using Logical AND

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

Tip: Avoid using a number directly on the left side of && when you do not want it displayed. For example, {0 &&

Hello

} renders 0. Use a comparison such as count > 0 instead.


13. Rule 11: Use Keys When Rendering Lists

When rendering multiple elements from an array using map(), provide a stable and unique key for each sibling element. Keys help React identify which items have changed, been added, or been removed.

Example

function App() {
  const courses = [
    { id: 1, name: "HTML" },
    { id: 2, name: "CSS" },
    { id: 3, name: "React JS" }
  ];

  return (
    <ul>
      {courses.map((course) => (
        <li key={course.id}>{course.name}</li>
      ))}
    </ul>
  );
}
export default App;

Explanation:

  • map() creates a list item for each course.
  • key={course.id} provides a stable identifier.
  • Keys should be unique among siblings and should remain stable across renders.

Avoid generating a new random key during every render. Array indexes should generally be avoided as keys when items may be reordered, inserted, or removed.


14. Rule 12: Use Correct JSX Style Syntax

The JSX style property accepts a JavaScript object rather than a CSS string. Most CSS property names use camelCase, and values generally use strings or numbers as appropriate.

Incorrect Example

<h1 style="color: blue; font-size: 30px;">
  Hello React
</h1>

Correct Example

function App() {
  return (
    <h1 style={{ color: "blue", fontSize: "30px" }}>
      Hello React
    </h1>
  );
}
export default App;

The outer curly braces introduce a JavaScript expression, while the inner braces define the style object.

Using a Separate Style Object

function App() {
  const headingStyle = {
    color: "blue",
    backgroundColor: "lightgray",
    padding: "10px"
  };

  return <h1 style={headingStyle}>Hello React</h1>;
}
export default App;

15. Rule 13: Handle Events Using JSX Event Props

React event handlers use props such as onClick, onChange, and onSubmit. Pass a function reference when you want React to call the function after an event occurs.

Correct Example

function App() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}
export default App;

Passing Arguments to an Event Handler

function App() {
  function greet(name) {
    alert("Hello, " + name);
  }

  return (
    <button onClick={() => greet("Rahul")}>
      Greet
    </button>
  );
}
export default App;

Remember: onClick={handleClick} passes the function. onClick={handleClick()} calls it during rendering, which is usually not what you want for an event handler.


16. Rule 14: Keep JSX Nesting Clear and Readable

Correct indentation and manageable component sizes make JSX easier to understand and maintain.

Less Readable Example

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

Recommended Example

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

Use consistent indentation, meaningful component names, and separate components when a UI section becomes too complex.


17. JSX Syntax Rules Summary

No. Rule Example
1 Return one root element.
...
or <>...
2 Close every tag. A
3 Use className for CSS classes. className="title"
4 Use camelCase for most JSX properties. onClick={handleClick}
5 Use curly braces for expressions. {name}
6 Use quotes for literal strings. alt="Profile photo"
7 Match opening and closing tags.

Hello

8 Capitalize custom component names.
9 Use parentheses for multiline JSX. return (
...
);
10 Use expressions for conditional UI. {isLoggedIn ? "Welcome" : "Login"}
11 Provide stable keys for list items. key={item.id}
12 Use an object for inline styles. style={{ color: "blue" }}
13 Pass functions to event props. onClick={handleClick}
14 Keep markup readable. Indent nested elements consistently.

18. Common JSX Errors and Solutions

Error Cause Solution
Adjacent JSX elements must be wrapped. Multiple sibling elements have no common parent. Use a parent element or Fragment.
Expected corresponding closing tag. A JSX tag is missing its closing tag. Close the tag or use self-closing syntax.
Incorrect CSS class property. Used class instead of className. Change it to className.
Dynamic value displays incorrectly. Variable is written as a quoted string. Use curly braces, such as {name}.
Custom component does not render correctly. Component name begins with a lowercase letter. Use an uppercase first letter.
List key warning. List elements lack appropriate keys. Use stable, unique keys.
Event handler runs immediately. Function is called during rendering. Pass a function reference or use an arrow function.
Inline styles are not applied. Style is written as a CSS string or uses incorrect property names. Use a JavaScript style object with camelCase properties.
Component returns nothing unexpectedly. A line break after return ends the statement. Place the JSX after return on the same line or use parentheses.

19. Practical Example: Student Information Card

This example combines several JSX rules, including a single root element, correctly closed tags, curly braces, camelCase properties, conditional rendering, and inline styles.

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

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

  return (
    <div className="student-card" style={cardStyle}>
      <h2>{student.name}</h2>
      <p>Course: {student.course}</p>
      <p>
        Status: {student.enrolled ? "Enrolled" : "Not Enrolled"}
      </p>
      <button onClick={() => alert(student.name)}>
        View Student
      </button>
    </div>
  );
}
export default StudentCard;

Concepts Used

  • A single root element: div.
  • Properly closed JSX tags.
  • className for CSS styling.
  • Curly braces for JavaScript expressions.
  • Conditional rendering with a ternary expression.
  • A style object for inline CSS.
  • An event handler for button clicks.

Practice Tasks

  1. Change the student's name and course.
  2. Add a student ID and display it using curly braces.
  3. Display a different message when enrolled is false.
  4. Add an image with a proper alt attribute.
  5. Create a list of three students using map() and stable keys.
  6. Move the styling into an external CSS file.

20. JSX Syntax and Rules – Interview Questions and Answers

Q1. What is JSX?

JSX is a JavaScript syntax extension that allows developers to write HTML-like markup inside JavaScript code, especially in React components.

Q2. Is JSX the same as HTML?

No. JSX resembles HTML but has stricter syntax and uses React-specific conventions for many attributes and expressions.

Q3. Why must JSX have a single root element?

A component must return a single JSX expression. Multiple sibling elements can be grouped inside a parent element or a Fragment.

Q4. Why do JSX tags need to be closed?

JSX requires explicit closing tags or self-closing syntax to define an unambiguous element structure.

Q5. Why is className used instead of class?

className is the JSX property used to assign CSS classes to React DOM elements.

Q6. What are curly braces used for in JSX?

They embed JavaScript expressions, such as variables, calculations, object properties, and function calls that return values.

Q7. What is a Fragment?

A Fragment groups JSX elements without adding an extra DOM element.

Q8. Why do React component names start with a capital letter?

Uppercase names distinguish custom React components from lowercase built-in HTML elements in JSX.

Q9. How are styles applied in JSX?

Styles can be applied using CSS classes, stylesheets, CSS modules, styling libraries, or inline style objects.

Q10. What is the purpose of the key property?

The key helps React identify list items between renders and should be stable and unique among sibling elements.

Q11. Can we use JavaScript if statements directly inside JSX braces?

No. JSX braces accept expressions, not standalone statements. Prepare conditional values before the return or use ternary expressions and logical operators.

Q12. Does the browser understand JSX directly?

No. JSX is transformed into JavaScript by a build tool or compatible transformation process before the browser executes it.


21. Quick Revision Checklist

  • Understand JSX syntax and its purpose.
  • Return one root element or use a Fragment.
  • Close all JSX tags.
  • Use className instead of class.
  • Use camelCase for most JSX properties.
  • Use curly braces for JavaScript expressions.
  • Use quotes for literal string attributes.
  • Use uppercase names for custom React components.
  • Use parentheses to format multiline JSX returns.
  • Write conditional rendering expressions correctly.
  • Use stable keys when rendering lists.
  • Use JavaScript objects for inline styles.
  • Pass event handler functions correctly.
  • Debug syntax errors using terminal and browser console messages.

22. Conclusion

JSX syntax and rules are fundamental to React development. Understanding root elements, closing tags, attributes, curly braces, component naming, event handling, conditional rendering, list keys, and inline styles helps developers build valid and maintainable React interfaces.

Practise these rules by creating small components and fixing common JSX errors before moving on to advanced React concepts such as props, state, Hooks, forms, API integration, and routing.

Explore React JS Training: JustAcademy React JS Training Course

Register for a Course Demo: Register for React JS Course Demo

Official Learning Resource: React – Writing Markup with JSX

whatsapp