You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
427 lines
13 KiB
427 lines
13 KiB
8 years ago
|
---
|
||
|
id: jsx-in-depth
|
||
|
title: JSX In Depth
|
||
|
permalink: docs/jsx-in-depth.html
|
||
8 years ago
|
redirect_from:
|
||
|
- "docs/jsx-spread.html"
|
||
|
- "docs/jsx-gotchas.html"
|
||
|
- "tips/if-else-in-JSX.html"
|
||
|
- "tips/self-closing-tag.html"
|
||
|
- "tips/maximum-number-of-jsx-root-nodes.html"
|
||
|
- "tips/children-props-type.html"
|
||
8 years ago
|
- "docs/jsx-in-depth-zh-CN.html"
|
||
|
- "docs/jsx-in-depth-ko-KR.html"
|
||
8 years ago
|
---
|
||
|
|
||
|
Fundamentally, JSX just provides syntactic sugar for the `React.createElement(component, props, ...children)` function. The JSX code:
|
||
|
|
||
|
```js
|
||
8 years ago
|
<MyButton color="blue" shadowSize={2}>
|
||
|
Click Me
|
||
|
</MyButton>
|
||
8 years ago
|
```
|
||
|
|
||
|
compiles into:
|
||
|
|
||
|
```js
|
||
8 years ago
|
React.createElement(
|
||
|
MyButton,
|
||
|
{color: 'blue', shadowSize: 2},
|
||
|
'Click Me'
|
||
|
)
|
||
8 years ago
|
```
|
||
|
|
||
|
You can also use the self-closing form of the tag if there are no children. So:
|
||
|
|
||
|
```js
|
||
|
<div className="sidebar" />
|
||
|
```
|
||
|
|
||
|
compiles into:
|
||
|
|
||
|
```js
|
||
8 years ago
|
React.createElement(
|
||
|
'div',
|
||
|
{className: 'sidebar'},
|
||
|
null
|
||
|
)
|
||
8 years ago
|
```
|
||
|
|
||
|
If you want to test out how some specific JSX is converted into JavaScript, you can try out [the online Babel compiler](https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-0&code=function%20hello()%20%7B%0A%20%20return%20%3Cdiv%3EHello%20world!%3C%2Fdiv%3E%3B%0A%7D).
|
||
|
|
||
|
## Specifying The React Element Type
|
||
|
|
||
|
The first part of a JSX tag determines the type of the React element.
|
||
|
|
||
|
Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX `<Foo />` expression, `Foo` must be in scope.
|
||
|
|
||
8 years ago
|
### React Must Be in Scope
|
||
|
|
||
8 years ago
|
Since JSX compiles into calls to `React.createElement`, the `React` library must also always be in scope from your JSX code.
|
||
|
|
||
8 years ago
|
For example, both of the imports are necessary in this code, even though `React` and `CustomButton` are not directly referenced from JavaScript:
|
||
8 years ago
|
|
||
8 years ago
|
```js{1,2,5}
|
||
8 years ago
|
import React from 'react';
|
||
|
import CustomButton from './CustomButton';
|
||
|
|
||
|
function WarningButton() {
|
||
8 years ago
|
// return React.createElement(CustomButton, {color: 'red'}, null);
|
||
8 years ago
|
return <CustomButton color="red" />;
|
||
|
}
|
||
|
```
|
||
|
|
||
8 years ago
|
If you don't use a JavaScript bundler and loaded React from a `<script>` tag, it is already in scope as the `React` global.
|
||
8 years ago
|
|
||
|
### Using Dot Notation for JSX Type
|
||
8 years ago
|
|
||
|
You can also refer to a React component using dot-notation from within JSX. This is convenient if you have a single module that exports many React components. For example, if `MyComponents.DatePicker` is a component, you can use it directly from JSX with:
|
||
|
|
||
8 years ago
|
```js{10}
|
||
8 years ago
|
import React from 'react';
|
||
|
|
||
8 years ago
|
const MyComponents = {
|
||
8 years ago
|
DatePicker: function DatePicker(props) {
|
||
|
return <div>Imagine a {props.color} datepicker here.</div>;
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
|
function BlueDatePicker() {
|
||
8 years ago
|
return <MyComponents.DatePicker color="blue" />;
|
||
8 years ago
|
}
|
||
|
```
|
||
|
|
||
8 years ago
|
### User-Defined Components Must Be Capitalized
|
||
|
|
||
8 years ago
|
When an element type starts with a lowercase letter, it refers to a built-in component like `<div>` or `<span>` and results in a string `'div'` or `'span'` passed to `React.createElement`. Types that start with a capital letter like `<Foo />` compile to `React.createElement(Foo)` and correspond to a component defined or imported in your JavaScript file.
|
||
|
|
||
|
We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.
|
||
|
|
||
|
For example, this code will not run as expected:
|
||
|
|
||
8 years ago
|
```js{3,4,10,11}
|
||
8 years ago
|
import React from 'react';
|
||
|
|
||
8 years ago
|
// Wrong! This is a component and should have been capitalized:
|
||
8 years ago
|
function hello(props) {
|
||
8 years ago
|
// Correct! This use of <div> is legitimate because div is a valid HTML tag:
|
||
8 years ago
|
return <div>Hello {props.toWhat}</div>;
|
||
|
}
|
||
|
|
||
|
function HelloWorld() {
|
||
8 years ago
|
// Wrong! React thinks <hello /> is an HTML tag because it's not capitalized:
|
||
8 years ago
|
return <hello toWhat="World" />;
|
||
|
}
|
||
|
```
|
||
|
|
||
8 years ago
|
To fix this, we will rename `hello` to `Hello` and use `<Hello />` when referring to it:
|
||
|
|
||
|
```js{3,4,10,11}
|
||
|
import React from 'react';
|
||
|
|
||
|
// Correct! This is a component and should be capitalized:
|
||
|
function Hello(props) {
|
||
|
// Correct! This use of <div> is legitimate because div is a valid HTML tag:
|
||
|
return <div>Hello {props.toWhat}</div>;
|
||
|
}
|
||
|
|
||
|
function HelloWorld() {
|
||
|
// Correct! React knows <Hello /> is a component because it's capitalized.
|
||
|
return <Hello toWhat="World" />;
|
||
|
}
|
||
|
```
|
||
|
|
||
|
### Choosing the Type at Runtime
|
||
|
|
||
8 years ago
|
You cannot use a general expression as the React element type. If you do want to use a general expression to indicate the type of the element, just assign it to a capitalized variable first. This often comes up when you want to render a different component based on a prop:
|
||
|
|
||
8 years ago
|
```js{10,11}
|
||
8 years ago
|
import React from 'react';
|
||
|
import { PhotoStory, VideoStory } from './stories';
|
||
|
|
||
|
const components = {
|
||
8 years ago
|
photo: PhotoStory,
|
||
|
video: VideoStory
|
||
8 years ago
|
};
|
||
|
|
||
8 years ago
|
function Story(props) {
|
||
|
// Wrong! JSX type can't be an expression.
|
||
|
return <components[props.storyType] story={props.story} />;
|
||
8 years ago
|
}
|
||
8 years ago
|
```
|
||
8 years ago
|
|
||
8 years ago
|
To fix this, we will assign the type to a capitalized variable first:
|
||
8 years ago
|
|
||
8 years ago
|
```js{10-12}
|
||
8 years ago
|
import React from 'react';
|
||
|
import { PhotoStory, VideoStory } from './stories';
|
||
|
|
||
|
const components = {
|
||
|
photo: PhotoStory,
|
||
|
video: VideoStory
|
||
|
};
|
||
|
|
||
|
function Story(props) {
|
||
|
// Correct! JSX type can be a capitalized variable.
|
||
|
const SpecificStory = components[props.storyType];
|
||
|
return <SpecificStory story={props.story} />;
|
||
8 years ago
|
}
|
||
|
```
|
||
|
|
||
|
## Props in JSX
|
||
|
|
||
|
There are several different ways to specify props in JSX.
|
||
|
|
||
8 years ago
|
### JavaScript Expressions as Props
|
||
8 years ago
|
|
||
|
You can pass any JavaScript expression as a prop, by surrounding it with `{}`. For example, in this JSX:
|
||
|
|
||
|
```js
|
||
|
<MyComponent foo={1 + 2 + 3 + 4} />
|
||
|
```
|
||
|
|
||
8 years ago
|
For `MyComponent`, the value of `props.foo` will be `10` because the expression `1 + 2 + 3 + 4` gets evaluated.
|
||
8 years ago
|
|
||
|
`if` statements and `for` loops are not expressions in JavaScript, so they can't be used in JSX directly. Instead, you can put these in the surrounding code. For example:
|
||
|
|
||
8 years ago
|
```js{3-7}
|
||
8 years ago
|
function NumberDescriber(props) {
|
||
8 years ago
|
let description;
|
||
8 years ago
|
if (props.number % 2 == 0) {
|
||
|
description = <strong>even</strong>;
|
||
|
} else {
|
||
|
description = <i>odd</i>;
|
||
|
}
|
||
|
return <div>{props.number} is an {description} number</div>;
|
||
|
}
|
||
|
```
|
||
|
|
||
7 years ago
|
You can learn more about [conditional rendering](/docs/conditional-rendering.html) and [loops](/docs/lists-and-keys.html) in the corresponding sections.
|
||
8 years ago
|
|
||
8 years ago
|
### String Literals
|
||
|
|
||
|
You can pass a string literal as a prop. These two JSX expressions are equivalent:
|
||
|
|
||
|
```js
|
||
|
<MyComponent message="hello world" />
|
||
|
|
||
8 years ago
|
<MyComponent message={'hello world'} />
|
||
8 years ago
|
```
|
||
|
|
||
|
When you pass a string literal, its value is HTML-unescaped. So these two JSX expressions are equivalent:
|
||
|
|
||
|
```js
|
||
|
<MyComponent message="<3" />
|
||
|
|
||
8 years ago
|
<MyComponent message={'<3'} />
|
||
8 years ago
|
```
|
||
|
|
||
|
This behavior is usually not relevant. It's only mentioned here for completeness.
|
||
|
|
||
|
### Props Default to "True"
|
||
|
|
||
|
If you pass no value for a prop, it defaults to `true`. These two JSX expressions are equivalent:
|
||
|
|
||
|
```js
|
||
|
<MyTextBox autocomplete />
|
||
|
|
||
|
<MyTextBox autocomplete={true} />
|
||
|
```
|
||
|
|
||
8 years ago
|
In general, we don't recommend using this because it can be confused with the [ES6 object shorthand](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) `{foo}` which is short for `{foo: foo}` rather than `{foo: true}`. This behavior is just there so that it matches the behavior of HTML.
|
||
8 years ago
|
|
||
|
### Spread Attributes
|
||
|
|
||
8 years ago
|
If you already have `props` as an object, and you want to pass it in JSX, you can use `...` as a "spread" operator to pass the whole props object. These two components are equivalent:
|
||
8 years ago
|
|
||
8 years ago
|
```js{7}
|
||
|
function App1() {
|
||
|
return <Greeting firstName="Ben" lastName="Hector" />;
|
||
8 years ago
|
}
|
||
|
|
||
8 years ago
|
function App2() {
|
||
|
const props = {firstName: 'Ben', lastName: 'Hector'};
|
||
|
return <Greeting {...props} />;
|
||
8 years ago
|
}
|
||
|
```
|
||
|
|
||
|
Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.
|
||
|
|
||
|
## Children in JSX
|
||
|
|
||
|
In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: `props.children`. There are several different ways to pass children:
|
||
|
|
||
|
### String Literals
|
||
|
|
||
|
You can put a string between the opening and closing tags and `props.children` will just be that string. This is useful for many of the built-in HTML elements. For example:
|
||
|
|
||
|
```js
|
||
|
<MyComponent>Hello world!</MyComponent>
|
||
|
```
|
||
|
|
||
|
This is valid JSX, and `props.children` in `MyComponent` will simply be the string `"Hello world!"`. HTML is unescaped, so you can generally write JSX just like you would write HTML in this way:
|
||
|
|
||
|
```html
|
||
|
<div>This is valid HTML & JSX at the same time.</div>
|
||
|
```
|
||
|
|
||
|
JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space. So these all render to the same thing:
|
||
|
|
||
|
```js
|
||
|
<div>Hello World</div>
|
||
|
|
||
|
<div>
|
||
|
Hello World
|
||
|
</div>
|
||
|
|
||
|
<div>
|
||
|
Hello
|
||
|
World
|
||
|
</div>
|
||
|
|
||
|
<div>
|
||
|
|
||
|
Hello World
|
||
|
</div>
|
||
|
```
|
||
|
|
||
|
### JSX Children
|
||
|
|
||
|
You can provide more JSX elements as the children. This is useful for displaying nested components:
|
||
|
|
||
|
```js
|
||
|
<MyContainer>
|
||
|
<MyFirstComponent />
|
||
|
<MySecondComponent />
|
||
|
</MyContainer>
|
||
|
```
|
||
|
|
||
|
You can mix together different types of children, so you can use string literals together with JSX children. This is another way in which JSX is like HTML, so that this is both valid JSX and valid HTML:
|
||
|
|
||
|
```html
|
||
|
<div>
|
||
|
Here is a list:
|
||
|
<ul>
|
||
|
<li>Item 1</li>
|
||
|
<li>Item 2</li>
|
||
|
</ul>
|
||
|
</div>
|
||
|
```
|
||
|
|
||
|
A React component can't return multiple React elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap it in a `div` like this.
|
||
|
|
||
8 years ago
|
### JavaScript Expressions as Children
|
||
8 years ago
|
|
||
|
You can pass any JavaScript expression as children, by enclosing it within `{}`. For example, these expressions are equivalent:
|
||
|
|
||
|
```js
|
||
|
<MyComponent>foo</MyComponent>
|
||
|
|
||
|
<MyComponent>{'foo'}</MyComponent>
|
||
|
```
|
||
|
|
||
|
This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:
|
||
|
|
||
8 years ago
|
```js{2,9}
|
||
8 years ago
|
function Item(props) {
|
||
|
return <li>{props.message}</li>;
|
||
|
}
|
||
|
|
||
8 years ago
|
function TodoList() {
|
||
8 years ago
|
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
|
||
8 years ago
|
return (
|
||
|
<ul>
|
||
|
{todos.map((message) => <Item key={message} message={message} />)}
|
||
|
</ul>
|
||
|
);
|
||
|
}
|
||
|
```
|
||
|
|
||
|
JavaScript expressions can be mixed with other types of children. This is often useful in lieu of string templates:
|
||
|
|
||
8 years ago
|
```js{2}
|
||
8 years ago
|
function Hello(props) {
|
||
|
return <div>Hello {props.addressee}!</div>;
|
||
|
}
|
||
|
```
|
||
|
|
||
8 years ago
|
### Functions as Children
|
||
|
|
||
8 years ago
|
Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of those things. However, `props.children` works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as `props.children`:
|
||
|
|
||
8 years ago
|
```js{4,13}
|
||
8 years ago
|
// Calls the children callback numTimes to produce a repeated component
|
||
|
function Repeat(props) {
|
||
8 years ago
|
let items = [];
|
||
8 years ago
|
for (let i = 0; i < props.numTimes; i++) {
|
||
8 years ago
|
items.push(props.children(i));
|
||
|
}
|
||
8 years ago
|
return <div>{items}</div>;
|
||
8 years ago
|
}
|
||
8 years ago
|
|
||
|
function ListOfTenThings() {
|
||
|
return (
|
||
|
<Repeat numTimes={10}>
|
||
|
{(index) => <div key={index}>This is item {index} in the list</div>}
|
||
|
</Repeat>
|
||
|
);
|
||
|
}
|
||
8 years ago
|
```
|
||
|
|
||
|
Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.
|
||
|
|
||
8 years ago
|
### Booleans, Null, and Undefined Are Ignored
|
||
|
|
||
|
`false`, `null`, `undefined`, and `true` are valid children. They simply don't render. These JSX expressions will all render to the same thing:
|
||
8 years ago
|
|
||
|
```js
|
||
|
<div />
|
||
|
|
||
|
<div></div>
|
||
|
|
||
|
<div>{false}</div>
|
||
|
|
||
|
<div>{null}</div>
|
||
|
|
||
8 years ago
|
<div>{undefined}</div>
|
||
|
|
||
8 years ago
|
<div>{true}</div>
|
||
|
```
|
||
|
|
||
8 years ago
|
This can be useful to conditionally render React elements. This JSX only renders a `<Header />` if `showHeader` is `true`:
|
||
8 years ago
|
|
||
8 years ago
|
```js{2}
|
||
|
<div>
|
||
|
{showHeader && <Header />}
|
||
|
<Content />
|
||
|
</div>
|
||
|
```
|
||
|
|
||
|
One caveat is that some ["falsy" values](https://developer.mozilla.org/en-US/docs/Glossary/Falsy), such as the `0` number, are still rendered by React. For example, this code will not behave as you might expect because `0` will be printed when `props.messages` is an empty array:
|
||
|
|
||
|
```js{2}
|
||
|
<div>
|
||
|
{props.messages.length &&
|
||
|
<MessageList messages={props.messages} />
|
||
|
}
|
||
|
</div>
|
||
|
```
|
||
|
|
||
|
To fix this, make sure that the expression before `&&` is always boolean:
|
||
|
|
||
|
```js{2}
|
||
|
<div>
|
||
|
{props.messages.length > 0 &&
|
||
|
<MessageList messages={props.messages} />
|
||
|
}
|
||
|
</div>
|
||
|
```
|
||
|
|
||
|
Conversely, if you want a value like `false`, `true`, `null`, or `undefined` to appear in the output, you have to [convert it to a string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion) first:
|
||
|
|
||
|
```js{2}
|
||
|
<div>
|
||
|
My JavaScript variable is {String(myVariable)}.
|
||
|
</div>
|
||
8 years ago
|
```
|