Filtering in Statamic using Livewire

120 Views Asked by At

I'm using Livewire for the first time. I have a Statamic Livewire component that displays a collection of blog articles with a default limit of 9 items. However, I noticed that on mobile devices (less than 768 pixels), I have to reduce the limit to 3 items. I'm trying to figure out how to dynamically adjust the limit based on the screen size.

Here is my code:

<?php

namespace App\Livewire;

use Livewire\Component;
use Statamic\Facades\Collection;

class FilterCollection extends Component
{
    public $taxonomyField;
    public $taxonomySlug;
    public $collectionName;
    public $viewName = 'collection';
    public $offset = 0;
    public $limit = 9;
    public $q;
    public $defaultSortBy = 'desc';
    public $sortBy;
    public $cards = [
        'blog_articles' => '_blog-list-card',
    ];

    public function render()
    {
        $newEntries = Collection::find($this->collectionName)
        ->queryEntries()
        ->where('published', 1)
        ->orderBy('date', $this->defaultSortBy)
        ->offset($this->offset)
        ->limit($this->limit);

        if (!empty($this->taxonomySlug)) {
            $newEntries->whereTaxonomy($this->taxonomyField . '::' . $this->taxonomySlug);
        }
        if (!empty($this->q)) {
            $newEntries->where(function ($query) {
                $query->where('title', 'like', '%' . $this->q . '%')
                    ->orWhere('article_summary', 'like', '%' . $this->q . '%')
                    ->orWhere('page_builder', 'like', '%' . $this->q . '%');;
            });
        }

        return view('livewire.filter-' . $this->viewName, ['entries' => $newEntries]);
    }

    public function filterCollection($taxonomySlug)
    {
        $this->taxonomySlug = $taxonomySlug;
    }

    public function loadMore()
    {
        $this->limit += $this->limit;
    }

    public function mount($collectionName, $taxonomyField = 'articles_tags', $q = null)
    {
        $this->collectionName = $collectionName ?? 'articles';
        $this->taxonomyField = $taxonomyField;
        $this->q = $q;
    }

}

The limit has the value of 9, but on mobile screens I need the limit to be adjusted to 3. How can I do that? I've tried to connect Livewire with Javascript, but I wasn't able to.

1

There are 1 best solutions below

2
Duncan McClean On

I'd probably try hiding the extra items with CSS media queries rather than doing anything on the backend.

Presuming you're using Antlers, you can do something like this on each item:

{{ entries }}
  <div {{ if index > 2 }} style="display: none" {{ /if }}>
    <h2>{{ title }}</h2>
    <!-- whatever other stuff you're doing... -->
  </div>
{{ /entries }}