Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React JSX

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:

Let's first look at the following code:

const element = 

Hello, world!

;

This tag syntax, which may look a bit strange, is neither a string nor HTML.

It is called JSX, a syntax extension of JavaScript. We recommend using JSX in React to describe the user interface.

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, and React DOM ensures that the data content of the browser DOM stays consistent with React elements.

To render React elements into the root DOM node, we pass them all to the ReactDOM.render() method to render them onto the page:

React example

const

element

= <

h1

className

=

"

foo

"

Hello

,

world

h1

;

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:

class → className:

Because class is a JavaScript keyword, className is used instead.

内容

htmlFor (inside labels):

Components starting with an uppercase letter:

Custom components must start with an uppercase letter (lowercase will be treated as HTML tags).

  {/* 正确,自定义组件 */}

  {/* 错误,会被当成  HTML 标签 */}

Note:

Use {/* comment content */}.

jsx{/* 这是一个 JSX 注释 */}

Root element:

return can only have one root node.

return (

  <>  {/* 碎片 Fragment,空标签,不渲染 DOM */}

    

标题

段落

);

We can open src/App.jsx and change return to:

return (

  <>

    

JSX 语法规则演示

Vite Logo
{/* 自闭合标签和注释 */}

注意 className 和闭合标签

);

Save and view the result.


Embedding expressions, conditional rendering, and list rendering

The most powerful thing about JSX is that you can embed JavaScript expressions in {} (only expressions, not statements such as if/for).

Embedding expressions

Any valid JS expression can be placed inside {}:

const name = 'runoob';

const now = new Date().toLocaleString();



return (

  

你好,{name}!

当前时间:{now}

计算结果:{2 + 3 * 5}

{/* 17 */}
);

Conditional Rendering

Use the ternary operator or &&:

const isLoggedIn = true;

const count = 0;



return (

  
{isLoggedIn ?

欢迎回来,{name}!

:

请登录

} {count > 0 &&

你有 {count} 条未读消息

} {/* count 为 0 时不渲染 */}
);

**Avoid:** do not use if statements directly in JSX (they can be used inside function bodies).

List rendering (the importance of key)

When rendering an array with map(), you must add a key attribute to each element (a unique identifier that helps React update the DOM efficiently).

const items = [

  { id: 1, name: '苹果' },

  { id: 2, name: '香蕉' },

  { id: 3, name: '橙子' },

];



return (

  
    {items.map(item => (
  • {/* key 必须唯一且稳定! */} {item.name}
  • ))}
);

The importance of key:

Style handling

React has several styling approaches; let's first learn the two most basic ones.

Inline styles (inline style)

Use the style attribute, whose value is an object (camelCase naming):

return (

  

内联样式示例

);

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 it in the component (scoped class names are generated automatically):

import styles from './styles/Card.module.css';



return (

  

标题

内容

);

**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 (

    
{imageUrl && {title}}

{title}

{content}

); }; export default Card;

Using JSX

JSX looks similar to HTML, let's look at an example:

const

element

= <

h1

className

=

"

foo

"

Hello

,

world

h1

;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

element

)

;

We can nest multiple HTML tags in the above code, but we need to wrap them with a div element. In the example, the p element has a custom attribute added. data-myattribute, to add a custom attribute you need to use data- prefix.

React example

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<

div

<

h1

Runoob Tutorial

h1

<

h2

Welcome to learning

React

h2

<p data myattribute="somevalue">

This is a very good

JavaScript

library!

p

div

)

;

Try it »

Separate file

Your React JSX code can be placed in a separate file. For example, we create a helloworld_react.js file with the following code:

const

element

= <

h1

className

=

"

foo

"

Hello

,

world

h1

;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

element

)

;

Then include this JS file in the HTML file:

React example

<body>
<div id="example" div>
<script type="text/babel" src="helloworld_react.js" script body>

Try it »


JavaScript Expressions

We can use JavaScript expressions in JSX. Expressions are written inside curly braces {} . Example below:

React example

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<div>
<h1{11}h1 div)>

;

Try it »

In JSX, you cannot use if else statements, but you can use conditional (ternary operation) expressions instead. In the following example, if the variable i Equal 1 the browser will output true, if the value of i is changed, it will output false.

React example

var

i

=

1

;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<div>
<h1{i==1?'>

True!

'

:

'

False

'

}

h1

div

)

;

Try it »


Style

React recommends using inline styles. We can use camelCase syntax to set inline styles. React automatically adds px after numbers in the specified element. The following example demonstrates setting h1 element, add myStyle inline styles:

React example

var

myStyle

=

{

fontSize

:

100

,

color

:

'

#FF0000

'

}

;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<h1 style={myStyle}>

Runoob Tutorial

h1

)

;

Try it »


Notes

Comments need to be written inside curly braces, example below:

React example

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<

div

<

h1

Runoob Tutorial

h1

{

/*

Comment...

*/

}

div

)

;

Try it »


arrays

JSX allows arrays to be inserted into templates, and the array will automatically expand all its members:

React example

var

arr

=

[

<

h1

Runoob Tutorial

h1

, <

h2

What you learn is not only technology, but also a dream!

h2

,

]

;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<div{arr}div)>

;

Try it »