The following code is raising an error:
{index % 2 === 0 && <div className='my-class'>}
Unexpected token, expected "," (9:14)
import AnotherComponent from './Anothercomponent.jsx'
export default function CurrentComponent({ datas, onChangeValue }) {
return (
<section>
{datas.map((data, index) => (
{index % 2 === 0 && <div className='my-wrapper'>}
<AnotherComponent/>
{index % 2 === 0 && </div>}
))}
</section>
);
}
the goal is to get this result:
<section>
<div class="my-class">
<AnotherComponent/>
<AnotherComponent/>
</div>
<div class="my-class">
<AnotherComponent/>
<AnotherComponent/>
</div>
</section>
Could you help please?
3
Answers
You can’t render a open and close element like that with a condition.
First of all, the
return
of amap
can only return a single DOM element, so you’ll need to wrap it in a div, or React.Fragment.But you still need to change the way you wrap it in a div.
Consider the following were we use an inline if statement to choose between
<AnotherComponent/>
in a<div>
<AnotherComponent/>
without a parentYou could also define a Wrapper component that will be the div or an empty Fragment:
A small demo showing the second example in a runnable react snippet:
In JSX, a conditional rendering is applicable on an
Element
and not with a single element tag.As others have stated, the issue is you can’t render a partial element.
will cause an error because the
div
element has no closing tag, react needs the entire component in a single expression.For your case, you can do something like this