Even/Odd in Blade loop with filtering

What seems to be the problem:
I would like to display a list of nested components and display them with zebra stripes, but I need the even/odd condition to update when items are filtered out and the remaining items change position.

student-list.blade.php

<div class="flex-1 overflow-y-auto">
                @foreach ($students as $student)
                @livewire('student-list-item', $student, $loop->even, key($student->id))
                @endforeach
</div>

StudentListItem.php

public function mount($student, $even)
    {
        $this->student = $student;
        $this->even = $even;
    }

student-list-item.blade.php

<a href="#"
    class="block p-4 border-b border-gray-200 hover:bg-blue-050 @if ($even) bg-gray-050 @else bg-white @endif @if ($selected) bg-blue-050 @endif"
    wire:click="$emit('setSelectedStudent', '{{ $student->id }}')">
    <h3>
        <span class="focus:text-indigo">{{ $student->last_name }}, </span>
        <span class="focus:text-indigo">{{ $student->first_name }}</span>
    </h3>
    <div class="mt-2 text-sm focus:text-indigo">{{ $student->email }}</div>
</a>

Obviously mount only runs once, so I get nice zebra stripes on load, but once I filter the results, the items all maintain their initial state. I assume I need to run an event of some sort but I’m coming up blank on how to implement that.

Are you using the latest version of Livewire: Yes

Do you have any screenshots or code examples: Above

Can’t you use the odd/even pseudo-classes?

2 Likes

I could if I wasn’t a clueless idiot! Thanks, that worked.

For other clueless idiots like me who stumble on this, you’ll need to add a variant to your tailwind.config.js to make this work:

  variants: {
          backgroundColor: ['responsive', 'odd', 'hover', 'focus'],
  },
1 Like