Self-closing
- React Native course
- Beginner
- Lesson 10/116
- 4 min
Learn self-closing tags and empty components.
Self-closing tags
If a tag will not contain anything, you write it in self-closing form. You do this by adding a / at the end, like <View />.
The self-closing form replaces an empty <View></View> pair; it is shorter and easier to read.
In JSX, any tag can be self-closing; just do not put children inside.
Using self-closing
Self-closing tags are a shorthand for an empty component. For example, you can write <View /> as a placeholder; it draws an empty box.
In JSX, any tag can be self-closing; but if a tag has children (other tags or text inside), self-closing cannot be used.
For an empty View write <View />; for a filled View write <View>...</View>.
Practice Use self-closing
Write an App component. Inside a <View> first place an empty <Text /> (self-closing), then <Text>Hello</Text>.
Starter code
// Use self-closing
function App() {
return null;
}Sample solution
function App() {
return (
<View>
<Text />
<Text>Hello</Text>
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is in self-closing form?
- <View /> Correct answer
- <View>
- <View>content</View>
- <View></View>
Explanation: <View /> is self-closing form.
2 Self-closing Text
<View>
____
<Text>Filled</Text>
</View>
<View>
<Text />
<Text>Filled</Text>
</View>
Explanation: <Text /> is the self-closing form of an empty Text.
3 Match the self-closing concepts
| Term | Meaning |
|---|---|
<View /> |
Empty View |
<Text /> |
Empty Text |
</Text> |
Closing |
/> |
Self-closing marker |