JSX Syntax and Rules in React
1. Introduction to JSX Syntax and Rules
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code. React developers use JSX to describe the structure and appearance of user interfaces. JSX follows specific syntax rules that help developers write readable, organized and valid React components.
Although JSX looks similar to HTML, it has some important differences, such as using className instead of class, closing every tag, wrapping multiple sibling elements in a single root and using curly braces to include JavaScript expressions.
Example of JSX Syntax
function App() {
return (
<div>
<h1>Welcome to React</h1>
<p>Learn JSX syntax and rules.</p>
</div>
);
}
export default App;
Explanation: The App function is a React component. It returns JSX containing a heading and a paragraph wrapped inside one parent element.
2. Basic Structure of JSX
JSX elements generally consist of an opening tag, content and a closing tag. Elements can contain text, other JSX elements, attributes and JavaScript expressions.
Example
const heading = <h1>Hello World</h1>;
In this example:
<h1> is the opening tag.
Hello World is the text content.
</h1> is the closing tag.
heading stores the JSX expression in a JavaScript variable.
JSX is transformed by compatible development tools into JavaScript that React can process. Browsers do not directly execute JSX syntax as written.
3. Rule One: Return a Single Root Element
A React component must return one JSX root element. If you want to return multiple sibling elements, you must wrap them inside a common parent element or a React Fragment.
Incorrect Example
function App() {
return (
<h1>Hello React</h1>
<p>Welcome to my website.</p>
);
}
Problem: The heading and paragraph are separate sibling elements without a common root.
Correct Example Using a div
function App() {
return (
<div>
<h1>Hello React</h1>
<p>Welcome to my website.</p>
</div>
);
}
Correct Example Using a Fragment
function App() {
return (
<>
<h1>Hello React</h1>
<p>Welcome to my website.</p>
</>
);
}
Important: A Fragment groups JSX elements without adding an extra DOM element to the rendered HTML.
4. Rule Two: Close All JSX Tags
JSX requires every element to be properly closed. Unlike HTML, where certain closing tags can be omitted, JSX requires explicit closing tags for elements and self-closing syntax for elements without children.
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="Website logo" />
</div>
);
}
Examples of properly closed JSX elements include:
<p>Paragraph</p>
<h1>Heading</h1>
<img src="/image.png" alt="Image" />
<br />
<input type="text" />
5. Rule Three: Use className Instead of class
In JSX, the HTML class attribute is generally written as className. This is because JSX attributes are represented as JavaScript properties, and className corresponds to the DOM property used for CSS classes.
HTML Example
<h1 class="main-heading">Welcome</h1>
JSX Example
function App() {
return (
<h1 className="main-heading">
Welcome
</h1>
);
}
CSS Example
.main-heading {
color: blue;
font-size: 32px;
text-align: center;
}
Explanation: The className attribute connects the JSX heading to the CSS class named main-heading.
6. Rule Four: Use camelCase for Most JSX Attributes
Many JSX attributes use camelCase rather than the lowercase or hyphenated forms commonly found in HTML. CamelCase means the first word starts with a lowercase letter and subsequent words begin with capital letters.
| HTML Attribute |
JSX Attribute |
Purpose |
class |
className |
Assigns a CSS class |
onclick |
onClick |
Handles a click event |
onchange |
onChange |
Handles a change event |
tabindex |
tabIndex |
Controls keyboard tab order |
readonly |
readOnly |
Makes a field read-only |
maxlength |
maxLength |
Sets a maximum input length |
stroke-width |
strokeWidth |
Sets an SVG stroke width |
Note: Some attributes, including aria-label and data-testid, retain their hyphenated spelling in JSX.
Example
function App() {
return (
<button
className="submit-button"
onClick={() => alert("Submitted!")}
>
Submit
</button>
);
}
7. Rule Five: Use Curly Braces for JavaScript Expressions
Curly braces {} allow developers to include JavaScript expressions inside JSX. Expressions can produce values such as strings, numbers, calculations, variable values or function results.
Example Using Variables
function App() {
const name = "Rahul";
const course = "React JS";
return (
<div>
<h1>Hello, {name}!</h1>
<p>Course: {course}</p>
</div>
);
}
Example Using Calculations
function App() {
const price = 500;
const quantity = 3;
return (
<p>Total Price: ₹{price * quantity}</p>
);
}
Example Using a Function
function App() {
function getMessage() {
return "Welcome to React development!";
}
return <h1>{getMessage()}</h1>;
}
Important: Use curly braces for JavaScript expressions, not for directly inserting statement blocks such as ordinary if statements or for loops. You can use conditional expressions such as a ternary operator inside JSX.
8. Rule Six: Understand Quoted Values and Curly-Brace Values
JSX attributes can contain fixed string values in quotation marks or dynamic JavaScript values inside curly braces. Understanding the difference prevents common mistakes.
Fixed String Value
function App() {
return <h1 title="Welcome Message">Hello</h1>;
}
Dynamic JavaScript Value
function App() {
const message = "Welcome Message";
return <h1 title={message}>Hello</h1>;
}
Incorrect Dynamic Value
function App() {
const message = "Welcome Message";
return <h1 title="{message}">Hello</h1>;
}
In the incorrect example, "{message}" is treated as a literal string rather than a reference to the JavaScript variable. Use title={message} to pass the variable value.
9. Rule Seven: Use Parentheses for Readable Multiline JSX
When JSX spans multiple lines, wrapping the returned markup in parentheses is a common practice. It improves readability and helps JavaScript parse the return expression as intended.
Example
function App() {
return (
<div className="container">
<h1>React Training</h1>
<p>Learn to build modern user interfaces.</p>
<button>Get Started</button>
</div>
);
}
export default App;
Parentheses are especially useful when a component returns nested elements, multiple attributes or conditional JSX. A short, single-line JSX expression may not need them.
10. Rule Eight: Use Proper JSX Nesting
JSX elements must be nested correctly. An element opened inside another element should be closed before its parent element is closed.
Incorrect Example
function App() {
return (
<div>
<p>Welcome to <strong>React</p></strong>
</div>
);
}
Problem: The strong element is closed after its parent paragraph has already closed.
Correct Example
function App() {
return (
<div>
<p>Welcome to <strong>React</strong></p>
</div>
);
}
Proper nesting makes JSX valid and helps keep the resulting document structure predictable.
11. Rule Nine: Use React Components with Capitalized Names
React component names must begin with a capital letter. Lowercase names are generally interpreted as built-in HTML tags, while capitalized names identify custom React components.
Example
function Header() {
return <h1>My Website</h1>;
}
function App() {
return (
<div>
<Header />
<p>Welcome to my website.</p>
</div>
);
}
export default App;
Here, Header is a custom React component and is used as <Header />. Naming it with an initial capital letter helps React distinguish it from standard HTML elements.
12. Rule Ten: Use Correct Event Handler Syntax
React event handlers use camelCase property names, such as onClick, onChange and onSubmit. A function reference is normally passed to the event attribute instead of calling the function immediately.
Correct Example
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
Passing Arguments to an Event Handler
function App() {
function greet(name) {
alert("Hello, " + name);
}
return (
<button onClick={() => greet("Priya")}>
Greet
</button>
);
}
Important: Writing onClick={handleClick()} calls the function while rendering. Use onClick={handleClick} to pass the function reference, or use an arrow function when arguments are required.
13. Rule Eleven: Use JavaScript Objects for Inline Styles
In JSX, the style attribute accepts a JavaScript object rather than a CSS text string. Most CSS property names use camelCase, and CSS values are often strings.
Example
function App() {
const headingStyle = {
color: "blue",
backgroundColor: "lightyellow",
fontSize: "28px",
textAlign: "center"
};
return (
<h1 style={headingStyle}>
Welcome to React
</h1>
);
}
Incorrect Example
<h1 style="color: blue; font-size: 28px">Welcome</h1>
Correct Example
<h1 style={{ color: "blue", fontSize: "28px" }}>
Welcome
</h1>
The outer curly braces indicate a JavaScript expression, and the inner braces create the JavaScript object containing CSS properties.
14. Rule Twelve: Use Stable Keys When Rendering Lists
When rendering multiple elements using methods such as map(), each list item should have a stable and unique key prop among its siblings. Keys help React identify which items have changed, moved, 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>
);
}
Best practice: Use a stable identifier from the data whenever possible. Avoid generating a new random key during every render. Array indexes may be unsuitable when list items can be reordered, inserted or deleted.
15. Rule Thirteen: Use Conditional Expressions Correctly
JSX supports conditional rendering through JavaScript expressions. The ternary operator is useful when choosing between two outputs, while logical AND is useful when an element should appear only when a condition is true.
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 hasMessage = true;
return (
<div>
<h1>Dashboard</h1>
{hasMessage && <p>You have a new message.</p>}
</div>
);
}
Note: Be careful when using logical AND with numeric values. For example, {0 && <p>Message</p>} can render the number 0. Use a Boolean comparison such as count > 0 when appropriate.
16. Rule Fourteen: Use Valid JSX Comments
Comments help developers explain their code. Inside JSX markup, comments use curly braces around JavaScript comment syntax.
Correct JSX Comment
function App() {
return (
<div>
{/* This is a JSX comment */}
<h1>Welcome to React</h1>
<p>Learn JSX step by step.</p>
</div>
);
}
For JavaScript code outside the returned JSX, normal JavaScript comments can be used.
// This is a JavaScript comment
function App() {
return <h1>Hello React</h1>;
}
17. Rule Fifteen: Understand Boolean and Other JSX Attributes
JSX attributes can receive strings, numbers, Boolean values and JavaScript expressions. Boolean attributes can be written with a value of true or false, or sometimes by using the attribute without a value to indicate true.
Example
function App() {
const isDisabled = true;
return (
<button disabled={isDisabled}>
Submit
</button>
);
}
In this example, the button is disabled because isDisabled is true.
Dynamic Image Attributes
function App() {
const imageUrl = "/images/profile.png";
const imageDescription = "Student profile";
return (
<img
src={imageUrl}
alt={imageDescription}
width={200}
/>
);
}
Curly braces allow the attribute values to come from JavaScript variables instead of fixed strings.
18. Common JSX Syntax Errors and Solutions
| Error |
Reason |
Solution |
| Multiple root elements |
Sibling elements are returned without a common root. |
Wrap them in a parent element or Fragment. |
| Missing closing tag |
An opening element is not closed. |
Close the element or use self-closing syntax. |
| Incorrect class attribute |
The HTML spelling is used in JSX. |
Use className. |
| Incorrect event name |
An event attribute uses lowercase naming. |
Use names such as onClick. |
| Incorrect nesting |
Child and parent tags are closed in the wrong order. |
Close nested elements in the correct order. |
| Variable shown as text |
A variable name is placed inside quotation marks. |
Use curly braces, such as {name}. |
| Invalid inline style |
A CSS string is passed to the style attribute. |
Use a JavaScript object. |
| Missing key warning |
Mapped elements do not have keys. |
Add a stable and unique key. |
| Component not recognized |
A custom component name begins with a lowercase letter. |
Use a capitalized component name. |
| Function runs immediately |
A handler is called directly in the event attribute. |
Pass a function reference or an arrow function. |
19. Practical Example: Student Information Card
The following example combines several JSX syntax rules in one component, including a single root element, correctly closed tags, attributes, JavaScript expressions, inline styling and event handling.
function StudentCard() {
const student = {
name: "Priya Sharma",
course: "React JS",
duration: "3 Months"
};
const cardStyle = {
border: "1px solid #ccc",
borderRadius: "10px",
padding: "20px",
maxWidth: "350px"
};
function handleClick() {
alert("Student: " + student.name);
}
return (
<div className="student-card" style={cardStyle}>
<h1>Student Information</h1>
<h2>{student.name}</h2>
<p>Course: {student.course}</p>
<p>Duration: {student.duration}</p>
<button onClick={handleClick}>
View Details
</button>
</div>
);
}
export default StudentCard;
What This Example Demonstrates
- The component returns one root
div.
- Every JSX element is correctly closed.
className assigns a CSS class.
- Curly braces display values from the student object.
- The inline style is provided as a JavaScript object.
- The button receives a function reference through
onClick.
20. Best Practices for JSX Syntax
- Always close JSX tags correctly.
- Wrap multiple sibling elements in a parent element or Fragment.
- Use
className instead of class.
- Use camelCase for most React event and DOM properties.
- Use curly braces for JavaScript expressions and dynamic attribute values.
- Use meaningful names for components, functions and variables.
- Keep the JSX indentation consistent and readable.
- Use stable keys for elements generated from lists.
- Use accessible attributes such as meaningful image alternative text.
- Use event handlers correctly by passing functions rather than calling them during rendering.
- Read compiler and browser console messages to help identify syntax problems.
- Keep components organized and avoid unnecessarily complicated JSX.
21. Frequently Asked Interview Questions
Q1. What is JSX syntax?
JSX syntax is a JavaScript syntax extension that lets developers write HTML-like markup inside JavaScript code, especially when building React components.
Q2. What are the main rules of JSX?
The main rules include returning a single root element, closing all tags, using className, using camelCase for most relevant attributes and placing JavaScript expressions inside curly braces.
Q3. Why does JSX require a single root element?
A component's returned JSX must describe one root value. Multiple sibling elements can be grouped using a parent element or Fragment.
Q4. Why do we use className instead of class?
className is the JSX property used to assign CSS classes to DOM elements.
Q5. What is the purpose of curly braces in JSX?
Curly braces allow JavaScript expressions, variable values, function results and dynamic values to be included in JSX.
Q6. Can we use if statements directly inside JSX?
Ordinary if statements cannot be placed directly inside JSX markup. You can use a ternary expression or logical AND inside JSX, or prepare a variable using an if statement before returning the JSX.
Q7. What is a Fragment in React?
A Fragment groups multiple JSX elements without adding an extra DOM element to the rendered output.
Q8. Why are JSX tags required to be closed?
JSX uses stricter markup syntax than HTML and requires elements to be explicitly closed or written using self-closing syntax.
Q9. How are event handlers written in JSX?
Event handlers use camelCase names such as onClick and usually receive a function reference.
Q10. What is the purpose of a key in JSX?
A key helps React identify list items between renders and update lists correctly.
22. Practice Exercises
- Create a component that displays a heading and two paragraphs inside one root element.
- Correct a JSX example that contains an unclosed image tag.
- Convert an HTML
class attribute to the correct JSX syntax.
- Display your name and age using curly braces.
- Create a button with a working
onClick event handler.
- Write a component that uses a Fragment instead of a div.
- Create an image using dynamic
src and alt variables.
- Display a list of programming courses using
map() and stable keys.
- Apply inline styling using a JavaScript object.
- Use a ternary expression to display a student's pass or fail status.
23. Quick Revision Checklist
- Understand the meaning of JSX syntax.
- Know how to return one root element.
- Understand how to use React Fragments.
- Know how and when to close JSX tags.
- Remember to use
className instead of class.
- Use camelCase for most JSX event and DOM attributes.
- Understand the difference between quoted strings and JavaScript expressions.
- Use curly braces to display dynamic values.
- Understand JSX event handlers, styles, conditions and list keys.
- Practice fixing common JSX syntax errors.
24. Conclusion
Understanding JSX syntax and rules is essential for building React applications. JSX makes it easier to describe user interfaces by combining markup with JavaScript expressions. By following the rules for root elements, closing tags, attributes, curly braces, component names, event handlers and list keys, developers can write clean, readable and maintainable React code.
25. Learn React JS with JustAcademy
Explore the React JS Training Course to strengthen your knowledge of JSX, React components and modern frontend 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
26. Official React Documentation
Read the official React guide for further explanations and practical examples of JSX syntax and rules.
React Official Documentation: Writing Markup with JSX
React Official Documentation: JavaScript in JSX with Curly Braces