Having A Loop To Change The Style Of A Card After Every Interval
Solution 1:
try using index in map to customize how you want it.
posts.map((item, idx) => (
<divclassName={idx === 0 ? "col-md-12" : "col-md-6col-sm-6"}><imgsrc={item?.src}alt={item?.caption}style={{minHeight: "280px", objectFit: "cover" }}
/></div>
Codesandbox https://codesandbox.io/s/sad-shannon-wkc28?file=/src/App.js
Solution 2:
I'm not use to help on this site but i maybe have an answer for you.
It seems your 'posts' only have 3 items so mapping on this wont make you have the 6 images you need. Whatever, you said the datas have to come frome your backend so i presume it's just some testing data.
I suggest you to use .map normally but define the differences with CSS. Then you can easily select the first and the last element of your mapping with something like that :
containerdiv:first-childdiv:first-child, containerdiv:last-childdiv:last-child{
//your css
}
But as you using bootsrap for styling, you need to translate the bootstrap classes for this method. I suggest you an other. The .map function can get an index as second argument. So you can do something like this :
posts.map(element, i => {yourcode} )
Then use the index for knowing if it is the first or the last item in a ternary expression :
i === 0 || i === posts.length ? your code for the first and last : normal code for the others
EDIT: I've try in the sandbox, it seems the problem with your patern is that every elements are not independents. The div element who appears every 3 items screw up everything for using map. My best result was this :
return (
<divclassName="App"><divclassName="container"><divclassName="row">
{posts &&
posts.map((item, i) => {
return (i+1)%4 === 0 || i===0 ?
(
<divclassName="col-md-6 col-sm-6"><divclassName="row"><divclassName={i === 0 || i === (posts.length-1) ? "col-md-12" : "col-md-6col-sm-6"}><imgsrc="https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg" /></div></div></div>
)
:
(
<divclassName="row"><divclassName={i === 0 || i === (posts.length-1) ? "col-md-12" : "col-md-6col-sm-6"}><imgsrc="https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg" /></div></div>)
})}
</div></div></div>
);
But i can't figuring out how handle this parent div for encapsulating every 3 element. Here a suggestion that i've not trying yet :
- Create a component who will mapping inside the problematic div.
- Find a way to create a 2D Array with your request, each Array in this one composed by 3 elements
- Mapping the 2D Array using your component.
The first mapping will map over each Array in your 2D array and the second map, inside your component, will map over the elements.
Post a Comment for "Having A Loop To Change The Style Of A Card After Every Interval"