Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rafwoski's avatar

[Flux UI] persist sidebar scroll postition

Hello, is there a way to persist sidebar scroll position between pages (using wire:naviagate) in flux? Can I just use Livewire @persist and wire:scroll ?

0 likes
1 reply
LaryAI's avatar
Level 58

To persist the sidebar scroll position between pages using Flux UI with wire:navigate, you can indeed use Livewire's @persist directive along with some JavaScript to handle the scroll position. Here's a step-by-step solution:

  1. Persist the Scroll Position:

    Use Livewire's @persist directive to store the scroll position in the session. You can create a Livewire component to handle this.

  2. JavaScript to Capture and Restore Scroll Position:

    Use JavaScript to capture the scroll position before navigation and restore it after the page loads.

Here's a basic implementation:

Livewire Component

Create a Livewire component to manage the scroll position.

// app/Http/Livewire/Sidebar.php

namespace App\Http\Livewire;

use Livewire\Component;

class Sidebar extends Component
{
    public $scrollPosition = 0;

    public function mount()
    {
        $this->scrollPosition = session()->get('sidebarScrollPosition', 0);
    }

    public function updatedScrollPosition($value)
    {
        session()->put('sidebarScrollPosition', $value);
    }

    public function render()
    {
        return view('livewire.sidebar');
    }
}

Blade View

In your Blade view, use the @persist directive and add JavaScript to handle the scroll events.

<!-- resources/views/livewire/sidebar.blade.php -->

<div id="sidebar" style="overflow-y: scroll; height: 100vh;" x-data="{ scrollPosition: @entangle('scrollPosition') }" x-init="$el.scrollTop = scrollPosition">
    <!-- Sidebar content here -->
</div>

<script>
    document.addEventListener('livewire:load', function () {
        const sidebar = document.getElementById('sidebar');

        sidebar.addEventListener('scroll', function () {
            Livewire.emit('updatedScrollPosition', sidebar.scrollTop);
        });

        Livewire.hook('message.processed', (message, component) => {
            if (component.fingerprint.name === 'sidebar') {
                sidebar.scrollTop = component.get('scrollPosition');
            }
        });
    });
</script>

Explanation

  • Livewire Component: The component manages the scroll position state and persists it in the session.
  • JavaScript: Listens for scroll events and updates the Livewire component with the current scroll position. When the component is re-rendered, it restores the scroll position.

This setup should help you maintain the sidebar scroll position across page navigations using wire:navigate. Adjust the component and view as needed to fit your specific application structure.

Please or to participate in this conversation.