Skip to content Skip to sidebar Skip to footer

React Component Closing Tag

I'm new to React and I'm trying to figure out the purpose/use of vs . I can't seem to find information on anything exce

Solution 1:

In React's JSX, you only need to write <MyComponent></MyComponent> when the component has child components, like this:

<MyComponent><Child /><Child /><Child /></MyComponent>

If there is nothing between <MyComponent> and </MyComponent>, then you can write it either <MyComponent/> or <MyComponent></MyComponent> (but <MyComponent/> is generally preferred). Details in Introducing JSX.

Just as a side note, you'd access those children in your component via the special props.children property. More in JSX in Depth: Children in JSX.

Note that this is very much not like HTML or XHTML. It's its own (similar) thing with different rules. For instance, in HTML, <div/> is exactly the same thing as <div>: A start tag, for which you must eventually have an end tag. Not so JSX (or XHTML). The rules for HTML are that void elements (elements that never have markup content, such as br or img) can be written with or without / before > and they never get an ending tag, but non-void elements (like div) must always have an ending tag (</div>), they cannot be self-closing. In JSX (and XHTML), they can be.

Solution 2:

The purpose of self-closing tags is simply the fact that it is more compact. This is especially useful when said component doesn't have any children that you typically wrap around a parent.

So usually for leaf components (i.e compoents that do not have any children), you use the self-closing syntax. Like: <Component />. And even if it has props, you can do: <Component foo="bar" />.

However, remember that children is a prop, so you could technically do:

<Component children={<span>foo</span>} />

but I find it less readable and advise against it (read disclaimer below).


To summarize, these are equivalent:

  • <Component /> = <Component></Component>
  • <Component foo="bar" /> = <Component foo="bar"></Component>
  • <Component children={<span>foo</span>}></Component> =

    <Component><span>foo</span></Component>

You can use whichever approach you prefer. Though praxis is to use the short-hand version when there are no children.


Disclaimer: While defining childen prop by its object key value will technically work, doing so is strongly discouraged as it disrupts the API as it is meant to be used. Use this version only if confident in what you are doing.

Post a Comment for "React Component Closing Tag"