What is the difference between <div /> and<div></div> or <Component /> and <Component> </Component>
<Layout home>
<section>
<h2>Blog</h2>
<ul>
{allPostsData.map(({ id, date, title }) => (
<li key={id}>
{title}
<br />
{id}
<br />
{date}
</li>
))}
</ul>
</section>
</Layout>
Who knows what I mean? Nowhere can I find a clear explanation of the differences between closing tags
2
Answers
Both of them are creating an React-Element. But you can use Self-closing tags (
<div />
) for If you do not have any Content nested inside, so an Empty-Element.So its equivalent to the closing-tags, when their do not have any children.
Means:
<div> </div>
is the same as<div />
So, if you do not have any content nested inside, you can use the self-closing tags.
Your code could look like this:
Well it’s quite easy, but to explain it the best I’ll start from the beginning.
When an elemene is all lowercase (
<div>
,<a>
…) it’s an HTML tag. If it starts with a capital letter, then it’s a React.js component.HTML tags can be opened (<>) or closed (</>). Most of the HTML elements require a closing tag (
<a> </a>
,<div> </div>
,<section> </section>
…), but there are the ones that are self-closing elements, aka the ones that don’t need a closing tag (<img>
,<link>
…).Those tags can be written as this –
<link />
,<img />
. That means they are self closing because they don’t have any content nested inside. Nested content is content that we place in between of<>
and</>
. If there is no content to be placed in between of those, then that element doesn’t require a closing tag.Let’s take
<img />
as an example. This element is used to import an image. We import it by specifying where the image is placed in the src attribute:<img src="path to your image">
. And that is it. So why write this element with a closing tag when there is nothing to close ?<img src="path to your image"></img>
. There is no nested content here so there is no need for a closing tag. It’s an empty element. So, we’ll write it like this:<img src="path to your image" />
.Same goes for React components. If your component is created and there is nothing to do with it but call it where you want it displayed, then you’ll write it self-closing:
<Component />
. But if you have some content to nest within it on the page where you’re displaying it, you’ll write it like this:<Component></Component>
.To sum up, if your element has no content to nest within it, then you’re going to self-close it –
<tag />
. If your element does have nested content, then you’ll need both opened and closed tag –<tag> </tag>
. So the difference between<div />
and<div></div>
or<Component />
and<Component> </Component>
is that<div />
has no nested content, but<div></div>
has. Same goes for the<Component>
.Hope I helped you understand it.