Can I use self-closing tag syntax for any HTML elements I use in JSX?

Question

Can I use self-closing tag syntax for any HTML elements I use in JSX?

Answer

You can! HTML elements we write in JSX can be self-closing as long as we use the forward-slash with right angle bracket to close the element tag.

For example:

<div className="myDiv" />

Now when would this be useful? Making a self-closing element is useful when said element has no children, this should be the only time we use self-closing syntax for HTML elements that are normally not self-closing.

13 Likes

Can I use self-closing tags on components? Or only closing tags?

2 Likes

It’s possible use nested self closing tags?

1 Like

I’m pretty sure the answer is no, based on my experience with normal html. Since this isn’t normal html though I could be wrong. If you find a way to do it then please let us know.

2 Likes

It works on components as well.

1 Like

Hi @saulayala1069007754, nested means having at least one child element, meaning you cannot use self-closing tags on the parent (due to having a child element). If, however, that same child element has no children of its own, you can use a self-closing tag on it.

1 Like

Why is there a space before the slash and do we always have to include that space?
Example: Using this <div> element:
<div id="main" />
I am referring to the space located right after the last " in "main" and right before the following / that goes to the closing bracket >.
i.e … <div id="main" <!--This space here-- > />

Could it be written as:
<div id="main"/>
And why is it not already written this way?

2 Likes

Hello, I believe it is just for code-readability purposes. White space does not have any effect in HTML or in JavaScript. But it just makes it easier to see that you are dealing with a self-closing tag.

1 Like