'alternate depending on whether their id is odd or even React
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>
);
}
Solution 1:[1]
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>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joshua Wood |
