1. What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React to describe the UI structure. It allows developers to write HTML-like code inside JavaScript. While it looks like HTML, JSX compiles to React.createElement calls, making it more efficient and readable for creating dynamic user interfaces.
2. Why Use JSX?
Readable and Intuitive: JSX makes it easier to visualize the structure of the UI and understand how the components are organized.
Tighter Integration with JavaScript: Since JSX is a syntax extension, it can seamlessly integrate JavaScript expressions, making the code more dynamic.
React Ecosystem: JSX is designed specifically for React, making it a natural choice for developing in the React ecosystem.
3. Writing basic JSX
JSX looks similar to HTML but with a few key differences. Here's a simple example of JSX syntax:
const element = Hello, World!
;
In this example:
<h1>Hello, World!</h1>
looks like an HTML tag, but it’s actually JSX. React transforms this into a React element.
const element
is a JavaScript constant that stores the JSX expression.
4. Embedding JavaScript in JSX
One of the key features of JSX is its ability to embed JavaScript expressions inside curly braces {}
const name = 'John';
const greeting = Hello, {name}!
;
In this example:
name
is embedded inside JSX using curly braces.
5. Important Notes on JSX Syntax
JSX must return a single element: If you have multiple elements, they must be wrapped inside a parent element, like a <div>
or a React Fragment (<>...</>
).
return (
<>
Title
This is a paragraph.
>
);
Self-closing tags: In JSX, elements that don't have children, such as <img />
or <br />
, must be written as self-closing.
const imgElement = ;
6. JSX vs. HTML
Although JSX looks similar to HTML, there are some important differences:
Class vs. className: In HTML, the class
attribute is used to define CSS classes. In JSX, this attribute is replaced with className
to avoid conflicts with JavaScript reserved keywords.
const button = ;
CamelCase Property Names: JSX uses camelCase naming conventions for attributes like onClick
or tabIndex
, whereas HTML uses lowercase.
const button = ;
JSX Expressions: Unlike HTML, you can embed JavaScript expressions directly in JSX using curly braces {}.
const num = 5;
const paragraph = {num * 10}
;