I have a flex grid that show items of different widths (rectangle, square, etc) and it pulls data from an API so the list is dynamic so each row is always different. This often results in "orphan" flex items at the end of the flex grid, especially at lower breakpoints.
I've noticed I usually only get 2 or 3 items lingering in the last row.
My goal is to only show full rows and get rid of all orphan items.
I thought of different ways to accomplish this and I noticed that all my orphan items are both 1) occurring when I shrink my screen below 1750px and 2) the orphan items are above 300px, large since they have no content next time to them that forces them to be small.
I thought I would add a resize event listener to check check only the last 6 items of my flex grid. If it's height is above 310, I add the style display: none , otherwise display: block.
this.throttledCheckOrphanItems = throttle(() => this.checkOrphanItems(), 300);
window.addEventListener('resize', this.throttledCheckOrphanItems);
checkOrphanItems() {
if (window.innerWidth > 1750) {
return;
}
const items = document.getQuerySelectorAll('.movieItems');
for (let x = items.length - 1; x >= items.length - 6; x--) {
const height = items[x].getBoundingClientRect().height;
if (height >= 310) {
items[x].style.display = 'none';
} else {
items[x].style.display = 'block';
}
}
},
It "works" but it is not a smooth experience.
I know this isn't a great solution but I can't find another way without sacrificing the setup of my grid. Is there a better way I can only show full rows? If not, is there a way to optimize my solution or make it more performant?