Self-Closing JSX Elements

JSX elements without children must use self-closing tag syntax. This syntax makes the absence of child content explicit and is required for empty JSX elements.

In JSX, an element that has no children is written with a slash before the closing angle bracket, such as `<img />` or `<Component />`. This is different from HTML, where some elements can be written without an explicit closing tag.

A self-closing element starts with `<` and ends with `/>`. The space before `/` is conventional, but the important part is that the slash closes the JSX element. JSX treats `</div>` and `` as equivalent when the element has no children.

Self-closing syntax applies to both native elements and user-defined React components. For example, `<input />`, `<Button />`, and `<UserCard />` are all valid forms when those elements have no child content.

If an element contains children, use an opening tag and a separate closing tag instead. For example, `Hello` contains text, so replacing it with `` would remove that content.

Key points

Interview questions

Why can't you simply write `<img>` in JSX as you might in HTML?

JSX has stricter XML-like tag syntax than ordinary HTML parsing. An element without children must be explicitly closed, commonly with `<img />`. This makes the JSX structure unambiguous to the JSX parser and compiler. The exact JSX transformation depends on the tooling and React setup, but the source syntax still requires the element to be closed.

What is the difference between `<Component />` and `<Component></Component>`?

Both represent a component with no children when the opening and closing forms contain nothing between them. The self-closing form is shorter and communicates the absence of children directly. The paired form is useful when content will be placed between the tags. If children are present, the paired form is required.

How do you write an element with no children in JSX?

Use self-closing syntax by placing `/` before the final `>`. For example, write `<img />` or `<MyComponent />`. This makes it explicit that the element has no children. If the element has children, use a separate closing tag instead.

Can React components use self-closing JSX syntax?

Yes. A custom component with no children can be written as `<UserCard />`. React treats this as a component element whose children are absent. If the component needs children, use `<UserCard>...</UserCard>` instead.