I am using React for a web page. In a component, I have a div on the left and an image on the right.
I would like them to alternate depending on whether their id is odd or even.
function Item({ title, text, link, img,id }) {
return (
<div >
<div>
<h3>
{title}
</h3>
<p>{text}</p>
<a href={link}>
text
</a>
</div>
<img src={img} alt={title} />
</div>
);
}
CodePudding user response:
Turn the div into a component and conditionally render them in the order you want:
function Item(props) {
return (
props.id % 2 == 0 ?
<div >
<Div {...props} />
<img src={img} alt={title} />
</div>
:
<div >
<img src={img} alt={title} />
<Div {...props} />
</div>
);
}
const Div = ({ title, text, link }) => (
<div>
<h3>
{title}
</h3>
<p>{text}</p>
<a href={link}>
text
</a>
</div>
)