Reputation: 635
I am new to react but have this snippet of code
return (
<div>
dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) :
(
<li className='goal-list-item-shown' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>
<div className='goal-info'>{goal.time_to_finish}</div>
)
</div>
)
If I don't use {} curly braces, I see the actual text, but if I put the curly braces around
{dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) :
(
<li className='goal-list-item-shown' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>
<div className='goal-info'>{goal.time_to_finish}</div>
)}
I get multiple errors that I can't figure out. I am denoting the javascript with curly braces and the executable code with parenthesis, and yet there are still issues syntax issues
The error shows up in the div nested within a list item with this response Line 12:17: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?
The issue seems to be with this line
<div className='goal-info'>{goal.time_to_finish}</div>
because when I remove it the errors go away, but I'm having a tough time figuring out why
Upvotes: 0
Views: 315
Reputation: 167
Within parenthesis ( .. ) you can only have single root jsx tag. So this would work:
(
<div>
<li className='goal-list-item-shown' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>
<div className='goal-info'>{goal.time_to_finish}</div>
</div>
)
Please refer forex. here for background: https://www.quora.com/Why-does-react-only-allow-one-DOM-element-to-be-rendered
Upvotes: 2
Reputation: 64
That’s because JSX elements must be wrapped with enclosing tag in React as the error message suggests. It is thrown because in your ternary expression the falsy value will return
<li></li>
<div></div>
without enclosing tag like this
<div>
<li></li>
<div></div>
</div>
If your goal is to eliminate the parent <div>
when it is parsed, you could use <React.Fragment>
to wrap the expression.
Upvotes: 0