Skip to content

JSX

🔍 What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows you to write HTML-like code inside JavaScript, making React code more readable and expressive.

JSX is not mandatory for React, but it is widely used because it simplifies the creation of React components by enabling HTML-like structure within JavaScript.


⚙️ How JSX Works

JSX allows you to write HTML-style syntax within your JavaScript code. Although it looks similar to HTML, it is actually JavaScript code that gets transformed into React.createElement() calls behind the scenes.

JSX Compilation Process:

  • React does not understand raw HTML. Therefore, JSX must be compiled into JavaScript.
  • This transformation is usually handled by a tool like Babel, which converts JSX into React.createElement() calls.

Example:

const element = <h1>Hello, MCA Students!</h1>;

This JSX code is compiled by Babel into:

const element = React.createElement('h1', null, 'Hello, MCA Students!');
  • The first argument 'h1' specifies the HTML tag.
  • The second argument is the props (which are null here, since there are no props).
  • The third argument is the content of the tag, i.e., 'Hello, MCA Students!'.

🧪 Key Features of JSX

1️⃣ HTML-Like Syntax

JSX looks similar to HTML, but it allows embedding JavaScript expressions directly inside curly braces {}. This makes it very intuitive for building dynamic UIs.

Example:

const user = 'Anjali';
const element = <h1>Hello, {user}!</h1>;

In the example above:

  • {user} is a JavaScript expression embedded within JSX.

2️⃣ Attributes in JSX

Just like HTML, JSX supports attributes (e.g., class, id, style), but with a few differences:

  • class is written as className in JSX.
  • for is written as htmlFor in JSX (to avoid conflicts with the JavaScript for keyword).
  • style is written as a JavaScript object in JSX.

Example:

const element = <div className="container" style={{ color: 'blue', fontSize: '20px' }}>Welcome!</div>;

3️⃣ Nesting Elements

JSX supports nesting of elements. You can place one JSX element inside another, just like you would with HTML.

Example:

const element = (
<div>
<h1>Welcome to ReactJS</h1>
<p>This is a JSX example.</p>
</div>
);

Here, <div> wraps both <h1> and <p> elements, making the code modular and easier to manage.


4️⃣ JavaScript Expressions Inside JSX

JSX allows you to insert any JavaScript expression within curly braces {}. This can include variables, functions, arithmetic expressions, or even calls to other components.

Example:

const num1 = 10;
const num2 = 5;
const sum = num1 + num2;

const element = <h1>Sum: {sum}</h1>;

Here, {sum} inside the JSX is evaluated as a JavaScript expression, and the result (15) will be rendered.


5️⃣ Self-Closing Tags

Just like HTML, JSX supports self-closing tags, which are useful when an element doesn’t have children.

Example:

jsxCopyEditconst element = <img src="logo.png" alt="React Logo" />;

6️⃣ Conditional Rendering in JSX

You can use JavaScript conditional logic within JSX to render elements based on certain conditions.

Example using the ternary operator:

const isLoggedIn = true;

const element = (
<h1>{isLoggedIn ? 'Welcome back!' : 'Please log in'}</h1>
);

This renders “Welcome back!” if isLoggedIn is true, and “Please log in” if false.


🔄 JSX vs. HTML

FeatureJSXHTML
SyntaxJavaScript with HTML-like syntaxStrictly HTML
Dynamic ContentCan embed JavaScript expressionsStatic content only
AttributesclassName, htmlFor, styleclass, for, style
Self-Closing TagsSupportedSupported
Event HandlersUse camelCase (e.g., onClick)Use lowercase (e.g., onclick)

🛠️ Common Mistakes with JSX

1️⃣ Returning Multiple Elements

JSX requires that you return one single parent element from a component. To return multiple elements, they must be wrapped in a single parent, like a <div> or <Fragment>.

Example:

// Correct:
const element = (
<div>
<h1>Hello</h1>
<p>Welcome to ReactJS</p>
</div>
);

// Incorrect (will throw error):
const element = (
<h1>Hello</h1>
<p>Welcome to ReactJS</p>
);

2️⃣ Not Closing Tags

In JSX, all tags must be self-closing when they don’t have content, just like in HTML5.

Example:

// Correct:
<input type="text" />

// Incorrect:
<input type="text">

🎯 Why Use JSX in React?

  1. Improves Readability: JSX makes the React code look more like HTML, which is familiar to developers.
  2. Easier to Understand: Embedding JavaScript expressions inside the markup simplifies the creation of dynamic UIs.
  3. React Ecosystem: JSX is tightly integrated with the React library, allowing easy interaction with React’s powerful features like state and props.

Best Practices for Using JSX

  • Keep it Simple: Use simple and readable JSX.
  • Avoid Inline Styles: Try to use CSS classes instead of inline styles for better performance.
  • Use Fragments: Use <React.Fragment> or shorthand <>...</> to return multiple elements without adding extra nodes to the DOM.
  • Break Down Large JSX: If JSX becomes too large or complex, split it into smaller components.

📚 Example of a React Component with JSX

import React from 'react';

function Greeting(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>Welcome to the world of ReactJS</p>
</div>
);
}

export default Greeting;

In this example:

  • We’re using JSX to return a div that contains an h1 and a p tag.
  • We’re dynamically rendering the name prop passed to the Greeting component.

🧑‍💻 Practice Tasks

  1. Create a Profile Card using JSX, displaying a name, image, and bio.
  2. Build a Counter App using JSX, where the count is rendered dynamically.
  3. Implement a To-Do List that dynamically adds tasks using JSX.

🔄 JSX Recap

  • JSX is an HTML-like syntax in JavaScript.
  • JavaScript expressions are embedded within curly braces {}.
  • JSX is compiled to React.createElement() behind the scenes.
  • Props and state are dynamically rendered in JSX.
  • Event handlers and conditional rendering are also handled within JSX.