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:
-
Persist the Scroll Position:
Use Livewire's
@persistdirective to store the scroll position in the session. You can create a Livewire component to handle this. -
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.