Rules of Writing JSX in React

Introduction to JSX Rules in React

JSX (JavaScript XML) is the syntax extension used in React to describe what the user interface should look like. It allows developers to write HTML-like code within JavaScript, making the code more intuitive and expressive. However, JSX is not exactly HTML. It comes with its own set of rules and guidelines that developers must follow to ensure their code compiles correctly and functions as expected. Understanding the rules of writing JSX is crucial for React development because even small mistakes can result in compilation errors.

This post will provide a complete overview of the rules of writing JSX in React, supported with examples, best practices, and explanations of why each rule matters.


Rule 1: JSX Must Have a Parent Element

In JSX, every expression must return a single parent element. Unlike HTML where you can write multiple top-level tags side by side, JSX does not allow this because it needs to compile into JavaScript function calls.

Example of Incorrect JSX:

function App() {
  return (
<h1>Hello World</h1>
<p>This will cause an error</p>
); }

This code will throw an error because two sibling elements are returned without a parent wrapper.

Correct JSX with Parent Element:

function App() {
  return (
<div>
  <h1>Hello World</h1>
  <p>This works correctly</p>
</div>
); }

Alternatively, React provides Fragments (<> </>) to wrap multiple elements without adding unnecessary nodes to the DOM.

Using React Fragment:

function App() {
  return (
&lt;&gt;
  &lt;h1&gt;Hello World&lt;/h1&gt;
  &lt;p&gt;This works too&lt;/p&gt;
&lt;/&gt;
); }

Rule 2: JSX Attributes Use CamelCase Naming

In HTML, attributes are written in lowercase (e.g., class, onclick). In JSX, attributes must follow camelCase conventions because they map to JavaScript object properties.

Example of Incorrect JSX:

<button onclick="handleClick()">Click Me</button> // Incorrect
<div class="container">Hello</div> // Incorrect

Correct JSX Syntax:

<button onClick={handleClick}>Click Me</button>
<div className="container">Hello</div>

Key points:

  • classclassName
  • forhtmlFor
  • Event handlers like onclickonClick

Rule 3: JSX Expressions Must Be Wrapped in Curly Braces

JSX allows embedding JavaScript expressions directly inside the markup, but these must be wrapped in curly braces {}.

Example of Using Expressions:

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

Here {name} is a JavaScript variable embedded inside JSX.

You can also use functions and arithmetic inside curly braces:

function App() {
  const num1 = 5;
  const num2 = 10;
  return <p>Sum: {num1 + num2}</p>;
}

Rule 4: JSX Attributes Can Take JavaScript Expressions

Along with text values, attributes in JSX can accept JavaScript expressions wrapped in curly braces.

Example:

function App() {
  const imageUrl = "https://example.com/logo.png";
  const altText = "Company Logo";
  return <img src={imageUrl} alt={altText} />;
}

This rule allows dynamic values for attributes instead of hardcoding them.


Rule 5: JSX Uses className Instead of class

Since class is a reserved keyword in JavaScript, JSX uses className to define CSS classes.

Example:

function App() {
  return <div className="card">This is a styled div</div>;
}

This ensures there is no conflict between JSX and JavaScript reserved keywords.


Rule 6: JSX Tags Must Be Properly Closed

Unlike HTML where some tags can remain open (e.g., <img>, <br>), in JSX all tags must be properly closed.

Incorrect JSX:

<img src="logo.png"> // Incorrect
<br> // Incorrect

Correct JSX:

<img src="logo.png" />
<br />

This is because JSX translates into JavaScript function calls, which require properly terminated syntax.


Rule 7: Conditional Rendering Requires JavaScript Expressions

JSX does not support traditional if-else inside markup directly. Instead, you must use JavaScript expressions like ternary operators or conditional functions.

Example Using Ternary Operator:

function App() {
  const isLoggedIn = true;
  return (
&lt;div&gt;
  {isLoggedIn ? &lt;h1&gt;Welcome Back&lt;/h1&gt; : &lt;h1&gt;Please Log In&lt;/h1&gt;}
&lt;/div&gt;
); }

Example Using Logical AND:

function App() {
  const hasMessages = true;
  return (
&lt;div&gt;
  {hasMessages &amp;&amp; &lt;p&gt;You have new messages&lt;/p&gt;}
&lt;/div&gt;
); }

Rule 8: Inline Styles Must Be Written as Objects

In JSX, inline styles are written as JavaScript objects where property names follow camelCase.

Incorrect JSX:

<div style="color: red; background-color: yellow;">Hello</div> // Incorrect

Correct JSX:

<div style={{ color: "red", backgroundColor: "yellow" }}>Hello</div>

Each property must be written in camelCase and wrapped inside double curly braces: one for JSX expression and one for object literal.


Rule 9: JSX Comments Must Be Written in Curly Braces

Comments inside JSX must be wrapped with curly braces.

Example:

function App() {
  return (
&lt;div&gt;
  {/* This is a JSX comment */}
  &lt;h1&gt;Hello World&lt;/h1&gt;
&lt;/div&gt;
); }

You cannot use standard HTML comments (<!-- -->) inside JSX.


Rule 10: JavaScript Reserved Keywords Cannot Be Used as Props Directly

Since JSX compiles into JavaScript, reserved keywords like for, class, and switch cannot be used directly. Instead, React provides alternatives such as htmlFor and className.

Example:

<label htmlFor="username">Username:</label>
<input id="username" type="text" />

Rule 11: Keys Must Be Unique for List Rendering

When rendering lists in JSX, each element must have a unique key attribute so React can track changes efficiently.

Example Without Keys (Incorrect):

function App() {
  const items = ["Apple", "Banana", "Cherry"];
  return (
&lt;ul&gt;
  {items.map((item) =&gt; (
    &lt;li&gt;{item}&lt;/li&gt;
  ))}
&lt;/ul&gt;
); }

This will show a warning in the console because each list item needs a key.

Example With Keys (Correct):

function App() {
  const items = ["Apple", "Banana", "Cherry"];
  return (
&lt;ul&gt;
  {items.map((item, index) =&gt; (
    &lt;li key={index}&gt;{item}&lt;/li&gt;
  ))}
&lt;/ul&gt;
); }

Rule 12: Boolean Attributes in JSX

In JSX, boolean attributes (like disabled, checked) can be written either as a full expression or shorthand.

Example:

<input type="checkbox" checked={true} />
<input type="checkbox" checked />

Both versions work correctly.


Rule 13: Spread Attributes for Props

React allows spreading props into JSX elements using the spread operator ....

Example:

const inputProps = {
  type: "text",
  placeholder: "Enter your name",
  className: "form-control"
};

function App() {
  return <input {...inputProps} />;
}

This helps pass multiple props efficiently.


Rule 14: JSX Is Case-Sensitive

Component names must be capitalized, while lowercase names are treated as HTML elements.

Example:

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

function App() {
  return (
&lt;div&gt;
  &lt;MyComponent /&gt; {/* Correct: Custom component */}
  &lt;mycomponent /&gt; {/* Incorrect: Will be treated as HTML tag */}
&lt;/div&gt;
); }

Rule 15: Avoid Injecting Objects Directly

Only strings, numbers, arrays, or React elements can be rendered directly. Objects must be transformed before use.

Incorrect JSX:

const user = { name: "John" };
<p>{user}</p> // Error

Correct JSX:

const user = { name: "John" };
<p>{user.name}</p>

Rule 16: JSX Cannot Use Statements Inside Markup

You cannot use control structures like loops (for, while) directly inside JSX. Instead, use array methods like .map().

Incorrect JSX:

function App() {
  for (let i = 0; i < 3; i++) {
return &lt;p&gt;{i}&lt;/p&gt;; // Incorrect
} }

Correct JSX with .map():

function App() {
  const numbers = [1, 2, 3];
  return (
&lt;div&gt;
  {numbers.map((num) =&gt; (
    &lt;p key={num}&gt;{num}&lt;/p&gt;
  ))}
&lt;/div&gt;
); }

Rule 17: Escape Characters in JSX

JSX supports escape characters for rendering text with special characters.

Example:

function App() {
  return (
&lt;div&gt;
  &lt;p&gt;This is a "quoted" text&lt;/p&gt;
  &lt;p&gt;2 &amp;lt; 5 is true&lt;/p&gt;
&lt;/div&gt;
); }

Rule 18: JSX Expressions Must Evaluate to a Value

Every expression inside curly braces must evaluate to something renderable (string, number, React element, etc.).

Incorrect JSX:

<p>{if (true) { return "Hello"; }}</p> // Error

Correct JSX:

<p>{true ? "Hello" : "Goodbye"}</p>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *