Say I’m wanting to render a piece of content, but certain factors may dictate whether it is rendered as a <span>
or as an <a>
, I would end up needing to write like:
<>
{someCondition
? <span>My content</span>
: <a ...>My content</span>
}
</>
but what I’m wondering is why we can’t render in this way instead, to shorthand/speed things up
<>
{someCondition ? <span> : <a ...>}
My content
{someCondition ? </span> : </a>}
</>
When I try to run this snippet I receive only an error at the point I’m attempting to render the closing </span>
tag…
3
Answers
Because jsx is not a string, it’s a tree of objects so
It is basically that syntax rules don’t allow you to do so. In JSX syntax, each opening tag needs to have a corresponding closing tag. The shorthand you proposed doesn’t follow that structure, which makes this syntacticly invalid.
If you don’t want to use your first example, you may try using a helper component to handle the conditional rendering:
You could somewhat get the desired output by defining the tag first before creating the JSX:
React Demo showing this: