I am trying to create a simple Alpine component (I’m using Laravel Livewire with Alpine JS) that has a list of items that should only show 3 at a time. Clicking on previous or next buttons should hide the current 3 displaying items and show the next/previous three items from the list. When the items showing update I would like a simple transition (x-transition) to work.
I think that the problem is when using x-transition in AlpineJS, it doesn’t work with the “template” tag (based on what the documentation mentions: https://alpinejs.dev/essentials/templating).
I’ve only used the “template” tag as that’s the only way I currently know to iterate through a list of items.
Is there an alternative method I can use to get it to work?
Here’s a simplified version of my current code:
<?php
$products = [
[
'url' => 'https://source.unsplash.com/featured/300x201',
'title' => 'ITEM ONE'
],
[
'url' => 'https://source.unsplash.com/featured/300x202',
'title' => 'ITEM TWO'
],
[
'url' => 'https://source.unsplash.com/featured/300x203',
'title' => 'ITEM THREE'
],
[
'url' => 'https://source.unsplash.com/featured/300x204',
'title' => 'ITEM FOUR'
],
[
'url' => 'https://source.unsplash.com/featured/300x205',
'title' => 'ITEM FIVE'
],
[
'url' => 'https://source.unsplash.com/featured/300x206',
'title' => 'ITEM SIX'
],
[
'url' => 'https://source.unsplash.com/featured/300x206',
'title' => 'ITEM SEVEN'
],
[
'url' => 'https://source.unsplash.com/featured/300x207',
'title' => 'ITEM EIGHT'
],
[
'url' => 'https://source.unsplash.com/featured/300x208',
'title' => 'ITEM NINE'
],
[
'url' => 'https://source.unsplash.com/featured/300x209',
'title' => 'ITEM TEN'
]
];
?>
<div x-data="{
items: @js($products),
startIndex: 0,
endIndex: 2,
}">
<template x-for="(item, index) in items.slice(startIndex, endIndex + 1)">
<div x-transition>
<img :src="item.url" alt="">
<p x-text="item.title"></p>
</div>
</template>
<button x-show="startIndex > 0" x-on:click="startIndex -= 3; endIndex -= 3;">
PREV
</button>
<button x-show="endIndex < items.length - 1" x-on:click="startIndex += 3; endIndex += 3;">
NEXT
</button>
</div>
Any help is much appreciated!