Tell us what’s happening:
Describe your issue in detail here.
I am quite confused about the use of {} in JSX. We were told to put JavaScript expression in {} but now we are told that JSX can also be appeared inside {}, like: {condition &&
markup
}. However, I tried the example below and found that it is invalid for top tag, but why? So what exactly are the rules of using {} in JSX?
Then the “shouldShowGreeting &&” is clearly JS. It’s just that the second half is JSX. If shouldShowGreeting is truthy, then the expression will evaluate to the JSX. If shouldShowGreeting is falsy, then it will evaluate to that. React is smart enough to know to ignore things like false or null or undefined so nothing gets displayed. You have to worry about things like 0 though, so if I don’t know that it will be safe, I often throw a double bang (!!) on the flag to make sure. (Part of this is from my React Native background where some falsy values can cause crashes.)
Does that makes sense? Yeah, it is a little weird. And the whole && thing is odd on its own - it’s not really a logical AND in the traditional sense but is a weird kind of selector, always evaluating to one of its values.
Sure, that could work, depending on your needs. Maybe I only want that div for that one situation. Or maybe there is other JSX there inside the div.
But your example is completely valid, it just depends on the situation. Of course, using the {} implies that there is surrounding JSX, but yeah, either example could work, just depending on what you want.
But yeah, the example I gave does look a little odd because why would you need that div if not showing the greeting. What about this example?
I come up a plausible reason: the {} here is a JSX way of interpretation and we need to have the tag (here in your example, the outest <div> tag) to trigger this special mode of interpretation. Otherwise, the {} will be interpreted as the delimiter for a block or a class.