Back to Freecodecamp

Learn About Self-Closing JSX Tags

curriculum/challenges/english/blocks/react/5a24c314108439a4d4036161.md

latest2.0 KB
Original Source

--description--

So far, you’ve seen how JSX differs from HTML in a key way with the use of className vs. class for defining HTML classes.

Another important way in which JSX differs from HTML is in the idea of the self-closing tag.

In HTML, almost all tags have both an opening and closing tag: <div></div>; the closing tag always has a forward slash before the tag name that you are closing. However, there are special instances in HTML called <dfn>void elements</dfn>, or elements that don’t require both an opening and closing tag before another element can start.

For example the line-break tag can be written as or as , but should never be written as </br>, since it doesn't contain any content.

In JSX, the rules are a little different. Any JSX element can be written with a self-closing tag, and every element must be closed. The line-break tag, for example, must always be written as in order to be valid JSX that can be transpiled. A <div>, on the other hand, can be written as <div /> or <div></div>. The difference is that in the first syntax version there is no way to include anything in the <div />. You will see in later challenges that this syntax is useful when rendering React components.

--instructions--

Fix the errors in the code editor so that it is valid JSX and successfully transpiles. Make sure you don't change any of the content - you only need to close tags where they are needed.

--hints--

The constant JSX should return a div element.

js
assert.strictEqual(JSX.type, 'div');

The div should contain a br tag.

js
assert(Enzyme.shallow(JSX).find('br').length === 1);

The div should contain an hr tag.

js
assert(Enzyme.shallow(JSX).find('hr').length === 1);

--seed--

--seed-contents--

jsx
const JSX = (
  <div>
    <h2>Welcome to React!</h2> 

    <p>Be sure to close all tags!</p>
    <hr >
  </div>
);

--solutions--

jsx
const JSX = (
<div>
  <h2>Welcome to React!</h2> 

  <p>Be sure to close all tags!</p>
  <hr />
</div>
);