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.
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.
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.
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?
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.