Flat Preloader Icon

Understanding JSX

Introduction to JSX

JSX stands for JavaScript XML. It is a syntax extension for JavaScript, which is used with React to describe what the UI should look like. With JSX, you can write HTML-like code within JavaScript files, making it easier to visualize the structure of your UI components.

Why Use JSX?

  1. Improved Readability: JSX makes it easier to write and understand the structure of the UI components.
  2. Better Developer Experience: It integrates well with JavaScript, allowing you to use JavaScript expressions and functions within your markup.
  3. Error Detection: Tools like Babel can transform JSX into JavaScript, providing better error messages and catching syntax errors early.

Basic Syntax

JSX allows you to write elements that look similar to HTML. Here’s an example:
				
					const element = <h1>Hello, world!</h1>;

				
			

Embedding Expressions

You can embed any JavaScript expression inside JSX by wrapping it in curly braces {}. This allows you to dynamically display data:
				
					const name = 'Ana';
const element = <h1>Hello, {name}!</h1>;

				
			

JSX Tags

JSX tags may contain children, allowing you to create nested structures:
				
					const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

				
			

JavaScript XML (JSX) Rules

1. JSX must have a single parent element

Each JSX expression must have one parent element.
				
					// Incorrect
const element = (
  <h1>Hello!</h1>
  <h2>Good to see you here.</h2>
);

// Correct
const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

				
			

2. Self-Closing Tags

JSX tags may be self-closing if they don’t have children.
				
					const element = <img decoding="async" src="image.jpg" />;

				
			

3. JSX Attributes:

In JSX, you use camelCase for attributes, rather than the lowercase convention in HTML.
				
					const element = <div className="my-class"></div>;

				
			

JSX Represents Objects

Babel compiles JSX down to React.createElement() calls. These calls create plain JavaScript objects that React uses to construct the DOM and update it efficiently.
				
					const element = <h1 className="greeting">Hello, world!</h1>;

// Compiles to:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);