Learn About Self-Closing JSX Tags

Learn About Self-Closing JSX Tags
0.0 0

#1

Tell us what’s happening:
I’m getting an error about JSX expressions needing one parent element

Your code so far


const JSX = (
  <div>
    {
    <h2>Welcome to React!</h2> <br />
    <p>Be sure to close all tags!</p>
    <hr />
    }
  </div>
);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/learn-about-self-closing-jsx-tags


#2

Hint: Anything between the { } is expected to be JavaScript, so having html between the { } is a problem. Just resolve this problem and you will pass the challenge, because you have correctly closed the tags which were open.


#3

Well, everything between the braces has to be valid JSX, which can be either plain JavaScript or HTMLish syntax, but crucially (and the reason OP is getting the error), a JSX expression using the HTMLish syntax must have a single parent element.

You can do something like this:

return (
  <div>
      <p />
      <p />
  </div>
);

Or this:

return (
  <div>
    {
      <p /> //it's tough being a single parent, but this `<p>` does it at the same time as holding down a full-time job!
    }
  </div>
);

But not this:

return (
  <div>
    {
      <p />
      <p /> //nope
    }
  </div>
);

#4

I have already fixed it realizing my dumb mistake. However I have another problem as I accidentally recursively called a component inside of itself and I can not fix it as my computer keeps on crashing. Is there anyway to reset my code from outside of the activity page?


#5

Thank you for catching my incorrect verbiage. For some reason I was thinking anything between the { } was interpreted strictly as JS. So the { } acts similar to the ( ) around the div element? Like a block? I am still fairly new to JSX and React, so it is good to learn something new.


#6

Try this (shortcuts work in Chrome, may vary in other browsers):

  • Open the page
  • Ctrl+ESC to open the browser task manager
  • Kill the page
  • Ctrl+Shift+J to open the browser console
  • Run localStorage.clear()
  • Reload with F5

#7

The parentheses () around the div are just for grouping. They are functionally equivalent to the parentheses in (1 + 2) * 3. In fact, they can often be omitted, but occasionally, omitting them will cause problems (similar to omitting semicolons).

I think (?) that’s correct that the braces {} do create a block scope, but their main purpose here is to signal to the compiler that we want the stuff between them to be interpreted as an expression. If that expression is a JSX block, we’d need further braces inside if we wanted to use other expressions. I can’t think of a use case where you’d want to do something like my #2 example, but it should at least compile with no problems.