JSX (JavaScript XML) is a JavaScript syntax extension that looks like XML. It is commonly used in React 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:
* High performance: After being compiled into JavaScript code, it is optimized to run faster;
* Type safety: Errors can be found at the compilation stage (even better when combined with TypeScript);
* Convenient to write: UI structure is intuitive and clear, embedding JavaScript expressions is more flexible, and writing templates is simple and fast;
* Essential characteristic: It is not a string/HTML, it will be compiled by Babel (built into Vite) into React.createElement calls.
Let's look at the following code first:
const element =
Hello, world!
;
This tag syntax, which may look somewhat strange, is neither a string nor HTML.
It is called JSX, a JavaScript syntax extension. 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, React elements 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 the root DOM node, we pass them to the ReactDOM.render() method to render them to the page:
## React Example
const element =
Hello, world
; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);
[Try it Β»](#)
> Note:
>
>
> Since JSX is JavaScript, identifiers like `class` and `for` are not recommended as XML attribute names. Instead, React DOM uses `className` and `htmlFor` as the corresponding attributes.
* * *
## JSX Syntax Rules
JSX looks like HTML, but has strict rules:
**Tags must be closed:**
* HTML can use , but JSX must use (self-closing).
* All tags must be closed: .
**class β className:**
Because class is a JavaScript keyword, use className instead.
Content
**htmlFor (inside labels):**
);
### Conditional Rendering
Use the ternary operator or &&:
const isLoggedIn = true;const count = 0;return (
{isLoggedIn ?
Welcome back, {name}!
:
Please log in
} {count > 0 &&
You have {count} unread messages
} {/* Will not render when count is 0 */}
);
**Avoid:** Do not use if statements directly in JSX (you can use them in the function body).
### List Rendering (Importance of key)
Use map() to render arrays, you must add a key attribute to each element (unique identifier, helps React update DOM efficiently).
const items = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Orange' },];return (
{items.map(item => (
{/* key must be unique and stable! */} {item.name}
))}
);
**Importance of key:**
* No key: React will warn, which may lead to rendering errors (especially when the list changes dynamically).
* Bad habit: Using index as key (key={index}) β when the list order changes, it will cause unnecessary re-renders or state loss.
* Best practice: Use unique IDs from the data (such as database id).
### Style Handling
React has multiple styling methods, let's learn the two most basic ones first.
#### Inline Style
Use the style attribute, the value is an object (camelCase):
return (
Inline Style Example
);
* Advantage: Dynamic styling is easy (variables can be used).
* Disadvantage: Not convenient for maintaining complex styles.
### CSS Modules (Recommended, scope 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 in the component (automatically generates scoped class names):
import styles from './styles/Card.module.css';return (
Title
Content
);
* Advantage: Class names are automatically hashed (e.g., .card__abc123), no conflicts.
**Complete Practice:** Modify 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 (
{imageUrl && }
{title}
{content}
);};export default Card;
* * *
## Using JSX
JSX looks similar to HTML, let's look at an example:
const element =
Hello, world
; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);
We can nest multiple HTML tags in the above code, which need to be wrapped in a div element. The p element in the instance adds a custom attribute **data-myattribute**. To add custom attributes, you need to use the **data-** prefix.
## React Example
const root = ReactDOM.createRoot(document.getElementById("root")); root.render(
Welcome to learning React
This is a pretty good JavaScript library!
);
[Try it Β»](#)
### Separate File
Your React JSX code can be placed in a separate file, for example, we create a `helloworld_react.js` file, the code is as follows:
const element =
Hello, world
; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element);
Then introduce the JS file in the HTML file:
## React Example
[Try it Β»](#)
* * *
## JavaScript