How use React JSX tag: Confused by this statement,when I use , it’s a compilation error

 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 />

Confused by this statement,when I use

, it’s a compilation error.

Learn About Self-Closing JSX Tags

the error is that you must return one element. try to put the self closing div inside the other div

1 Like

First of all, thank you for your answer.
But I still don’t really understand.
Which scenarios can use <div /> alone?

We use this <div /> in JSX when an element has no children and when children are present we use this <div></div>

It differs from the normal HTML closing tag, </div> because it’s JSX.

1 Like

First of all, thank you for your answer.

const JSX = (
  <div id="1">
    <h2>Welcome to React!</h2> <br/>
    <p>Be sure to close all tags!</p>
    <hr />
  </div>

  <div id="2" />
);

The div element with id = 2 is the one I use directly,no child elements,just only one div element of the same level with id=1.

The expected result should be that it compiles and passes.

The actual effect is that the exception is thrown.

because your JSX variable should have one element that wrap everything, so your code is not valid.

before, the div#1 was around all the other elements, so it was fine. Now you added div#2 outside, so it’s not fine anymore.
You need to write something like below, using the fragment, or using a proper element. That’s why earlier I told you to put div#2 inside div#1 to avoid the error, but as you don’t want to do that, this is an other alternative.

const JSX = (
<>
  <div id="1">
    <h2>Welcome to React!</h2> <br/>
    <p>Be sure to close all tags!</p>
    <hr />
  </div>

  <div id="2" />
</>
);
1 Like

Think of it as a function return. Functions can only return one value, if you want to return multiple values you have to wrap them in an array or object. The outer element is the wrapper, you can return multiple nested elements as long as they are wrapped inside one outer element.

It makes a little more sense after you understand how JSX and createElement works.


There isn’t a ton of use cases for <div /> (unlike <Component someProp="someVal" />) but it could be an empty element with some CSS used for layout <div className="h-spacer" /> but that should likely be a component anyway.

1 Like

Thanks a million, I understand. :heart:

Thanks a million, I understand. :sparkling_heart:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.