React JSX
JSX (JavaScript XML) is a JavaScript syntax extension that looks like XML. In React, it is often used instead of regular JavaScript to write UI components, allowing you to describe component structure and behavior in an HTML-like way.
Using JSX is not mandatory, but it has the following core advantages:
- Efficient execution: After compilation into JavaScript code, it is optimized and runs faster;
- Type safety: Errors can be found at compile time (even better with TypeScript);
- Convenient writing: UI structure is intuitive and clear, embedding JavaScript expressions is more flexible, and writing templates is simple and fast;
- Essential nature: It is not a string/HTML; it is compiled into React.createElement calls by Babel (built into Vite).
Let's first look at the following code:
const element = <h1>Hello, world!</h1>;
This seemingly strange tag syntax is neither a string nor HTML.
It is called JSX, a syntax extension of JavaScript. We recommend using JSX in React to describe user interfaces.
JSX is implemented inside JavaScript.
We know that elements are the smallest units that make up a React application, and JSX is used to declare elements in React.
Unlike browser DOM elements, elements in React are actually plain objects. React DOM ensures that the data content of the browser DOM stays consistent with the React elements.
To render React elements into a root DOM node, we pass them all to ReactDOM.render() to render them on the page:
React Example
Try it »
Note:
Since JSX is JavaScript, some identifiers like
classandforare not recommended as XMLclassNameandhtmlForattribute names. Instead, React DOM uses
JSX Syntax Rules
JSX Syntax Rules
JSX looks like HTML, but has strict rules:
- HTML can<br>, but JSX must<br />(self-closing).
- All tags must be closed:<div></div>。
class → className:
Because class is a JavaScript keyword, use className instead.
<div className="container">内容</div>
htmlFor (inside label):
<label for="id"> → <label htmlFor="id">
Components starting with an uppercase letter:
Custom components must start with an uppercase letter (lowercase will be treated as HTML tags).
<Card /> {/* 正确,自定义组件 */}
<card /> {/* 错误,会被当成 <card> HTML 标签 */}
Comments:
use{/* comment content */}。
jsx{/* 这是一个 JSX 注释 */}
Root element:
return can only have one root node.
return (
<> {/* 碎片 Fragment,空标签,不渲染 DOM */}
<h1>标题</h1>
<p>段落</p>
</>
);
We can open src/App.jsx and change the return to:
return (
<>
<h1 className="title">JSX 语法规则演示</h1>
<img src="../vite.svg.html" alt="Vite Logo" />
<br />
{/* 自闭合标签和注释 */}
<p>注意 className 和闭合标签</p>
</>
);Save to see the effect.
Expression Embedding, Conditional Rendering, List Rendering
The most powerful feature of JSX is that you can use {} to embed JavaScript expressions (only expressions, not statements like if/for).
Expression Embedding
Any valid JS expression can be placed inside{}:
const name = 'example';
const now = new Date().toLocaleString();
return (
<div>
<h1>你好,{name}!</h1>
<p>当前时间:{now}</p>
<p>计算结果:{2 + 3 * 5}</p> {/* 17 */}
</div>
);
Conditional Rendering
Use ternary operators or&&:
const isLoggedIn = true;
const count = 0;
return (
<div>
{isLoggedIn ? <h1>欢迎回来,{name}!</h1> : <h1>请登录</h1>}
{count > 0 && <p>你有 {count} 条未读消息</p>} {/* count 为 0 时不渲染 */}
</div>
);
Avoid:Do not use if statements directly in JSX (they can be used inside function bodies).
List Rendering (Importance of key)
Use map() to render arrays. You must add a key attribute to each element (a unique identifier that helps React efficiently update the DOM).
const items = [
{ id: 1, name: '苹果' },
{ id: 2, name: '香蕉' },
{ id: 3, name: '橙子' },
];
return (
<ul>
{items.map(item => (
<li key={item.id}> {/* key 必须唯一且稳定! */}
{item.name}
</li>
))}
</ul>
);Importance of key:
- Without key: React will warn, which may cause rendering errors (especially when the list changes dynamically).
- Bad habit: using index as the key (key={index}) — when the order of the list changes, it can cause unnecessary re-renders or state loss.
- Best practice: use a unique ID from the data (such as database id).
Styling
React has multiple styling approaches; let's first learn the two most basic ones.
Inline styles
Use the style attribute, whose value is an object (camelCase):
return (
<div
style={{
backgroundColor: '#F0F0F0',
padding: '20px',
borderRadius: '8px',
textAlign: 'center',
fontFamily: 'Arial, sans-serif',
}}
>
<h2 style={{ color: 'blue', marginBottom: '10px' }}>
内联样式示例
</h2>
</div>
); - Advantage: dynamic styles are easy (variables can be used).
- Disadvantage: not convenient for maintaining complex styles.
CSS Modules (Recommended, Scoped Isolation)
Vite supports CSS Modules by default, avoiding global pollution.
Create src/App.css (already exists) or a new file src/styles/Card.module.css:
/* Card.module.css */
.card {
background: white;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
padding: 20px;
margin: 20px;
}
.title {
color: #333;
margin: 0 0 10px 0;
}
.content {
color: #666;
}Import and use it in the component (scoped class names are automatically generated):
import styles from './styles/Card.module.css';
return (
<div className={styles.card}>
<h3 className={styles.title}>标题</h3>
<p className={styles.content}>内容</p>
</div>
);
- Advantage: class names are automatically hashed (e.g., .card__abc123), so there are no conflicts.
Complete practice:Change the previous Card component to use CSS Modules.
Create src/components/Card.module.css:
.container {
width: 300px;
border: 1px solid #ccc;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
background: white;
}
.image {
width: 100%;
height: 200px;
object-fit: cover;
}
.title {
margin: 0 0 10px 0;
padding: 20px 20px 0;
color: #333;
}
.content {
padding: 0 20px 20px;
color: #666;
}Modify Card.jsx:
import styles from './Card.module.css';
const Card = ({ title, content, imageUrl }) => {
return (
<div className={styles.container}>
{imageUrl && <img src={imageUrl} alt={title} className={styles.image} />}
<h3 className={styles.title}>{title}</h3>
<p className={styles.content}>{content}</p>
</div>
);
};
export default Card;
Using JSX
JSX looks similar to HTML; we can look at an example:
We can nest multiple HTML tags in the above code, and need to wrap them with a div element. The p element in the example has a custom attributedata-myattribute, to add custom attributes, you need to usedata-prefix.
React Example
Try it »
Separate File
Your React JSX code can be placed in a separate file, for example we create ahelloworld_react.jsfile, the code is as follows:
Then include the JS file in the HTML file:
React Example
Try it »
JavaScript Expressions
We can use JavaScript expressions in JSX. Expressions are written in curly braces{}inside. The example is as follows:
React Example
Try it »
In JSX, you cannot useif elsestatements, but you can useconditional (ternary operation)expression instead. In the following example, if the variableiequals1the browser will outputtrue, if the value of i is changed, it will outputfalse.
React Example
Try it »
Styles
React recommends using inline styles. We can usecamelCasesyntax to set inline styles. React will automatically add after the specified element numberpx. The following example demonstrates for theh1element, addingmyStyleinline style:
React Example
Try it »
Comments
Comments need to be written in curly braces, for example:
React Example
Try it »
Arrays
JSX allows inserting arrays into templates, and the array automatically expands all members:
React Example
Try it »