YouTip LogoYouTip

React Jsx

JSX (JavaScript XML) is a JavaScript syntax extension that looks like XML. In React, it is commonly used instead of regular JavaScript to write UI components, allowing you to describe component structure and behavior in an HTML-like manner. Using JSX is not mandatory, but it offers the following core advantages: * Efficient Execution: After being compiled into optimized JavaScript code, it runs faster; * Type Safety: Errors can be caught during compilation (especially effective when used with TypeScript); * Convenient Writing: The 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, but will be compiled by Babel (built into Vite) into React.createElement calls. Let's first look at the following code: ```jsx const element =

Hello, world!

; This tag syntax that might look a bit strange is neither a string nor HTML. It is called JSX, a syntax extension for JavaScript. We recommend using JSX in React to describe user interfaces. JSX is implemented within 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, and React DOM ensures that the browser DOM data content remains consistent with React elements. To render React elements into the root DOM node, we render them to the page by passing them to the `ReactDOM.render()` method: ## React Example ```jsx const element =

Hello, world

; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element); [Try it Β»](#) > Note: > > Since JSX is JavaScript, some identifiers like `class` and `for` are not recommended as XML attribute names. Instead, React DOM uses `className` and `htmlFor` for the corresponding attributes. * * * ## JSX Syntax Rules JSX looks like HTML, but has strict rules: **Tags must be closed:** * HTML can have `
`, but JSX must have `
` (self-closing). * All tags must be closed: `
`. **class β†’ className:** Because `class` is a JavaScript keyword, use `className` instead. ```jsx
Content
**htmlFor (within tags):** `
); ### Conditional Rendering Use the ternary operator or `&&`: ```jsx const isLoggedIn = true; const count = 0; return (
{isLoggedIn ?

Welcome back, {name}!

:

Please log in

} {count > 0 &&

You have {count} unread messages

} {/* Does not render when count is 0 */}
); **Avoid:** Do not use `if` statements directly inside JSX (they can be used within the function body). ### List Rendering (The Importance of `key`) Use `map()` to render arrays, and you must add a `key` attribute to each element (a unique identifier that helps React update the DOM efficiently). ```jsx 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}
  • ))}
); **The Importance of `key`:** * Without `key`: React will warn you, and it may cause rendering errors (especially when the list changes dynamically). * Bad Habit: Using the index as the key (`key={index}`) β€” when the list order changes, it can cause unnecessary re-renders or state loss. * Best Practice: Use a unique ID from the data (like a database ID). ### Styling React has multiple ways to style components. Let's first learn two of the most basic ones. #### Inline Styles Use the `style` attribute, with the value being an object (camelCase naming): ```jsx return (

Inline Style Example

); * Advantage: Easy to apply dynamic styles (can use variables). * 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`: ```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 (automatically generates scoped class names): ```jsx import styles from './styles/Card.module.css'; return (

Title

Content

); * Advantage: Class names are automatically hashed (e.g., `.card__abc123`), preventing conflicts. **Complete Practice:** Modify the previous Card component to use CSS Modules. Create `src/components/Card.module.css`: ```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`: ```jsx import styles from './Card.module.css'; const Card = ({ title, content, imageUrl }) => { return (
{imageUrl && {title}}

{title}

{content}

); }; export default Card; * * * ## Using JSX JSX looks similar to HTML. Let's look at an example: ```jsx const element =

Hello, world

; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element); We can nest multiple HTML tags in the above code, and we need to use a `div` element to wrap them. The `p` element in the example has a custom attribute **data-myattribute**. Adding custom attributes requires using the **data-** prefix. ## React Example ```jsx const root = ReactDOM.createRoot(document.getElementById("root")); root.render(

Welcome to Learn React

This is a great JavaScript library!

); [Try it Β»](#) ### Separate Files Your React JSX code can be placed in a separate file. For example, we create a `helloworld_react.js` file with the following code: ```jsx const element =

Hello, world

; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(element); Then import this JS file in the HTML file: ## React Example
[Try it Β»](#) * * * ## JavaScript Expressions We can use JavaScript expressions in JSX. Expressions are written inside curly braces **{}**. Here is an example: ## React Example ```jsx const root = ReactDOM.createRoot(document.getElementById("root")); root.render(

{1+1}

); [Try it Β»](#) You cannot use **if else** statements in JSX, but you can use **conditional (ternary operator)** expressions instead. In the following example, if the variable **i** equals **1**, the browser will output **true**. If you change the value of `i`, it will output **false**. ## React Example ```jsx var i = 1; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(

{i == 1 ? 'True!' : 'False'}

); [Try it Β»](#) * * * ## Styles React recommends using inline styles. We can use **camelCase** syntax to set inline styles. React will automatically add **px** after specified numeric values. The following example demonstrates adding an inline style **myStyle** to the **h1** element: ## React Example ```jsx var myStyle = { fontSize: 100, color: '#FF0000' }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(

); [Try it Β»](#) * * * ## Comments Comments need to be written inside curly braces. Here is an example: ## React Example ```jsx const root = ReactDOM.createRoot(document.getElementById("root")); root.render(

{/* This is a comment */}
); [Try it Β»](#) * * * ## Arrays JSX allows inserting arrays into templates, and the array will automatically expand all its members: ## React Example ```jsx var arr = [

,

Learning is not just about technology, but also about dreams!

, ]; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(
{arr}
); [Try it Β»](#)
← React JsxReact Tutorial β†’