wire:navigate

The wire:navigate directive provides SPA-like page navigation by intercepting link clicks and loading pages in the background. Instead of full page refreshes, Livewire fetches new content and swaps it seamlessly, resulting in faster navigation and a smoother user experience.

Basic Usage

This navigation example demonstrates wire:navigate with hover prefetching and redirect functionality:

// wires/BlogPost.bx
class extends="cbwire.models.Component" {
    data = {
        "title": "",
        "content": ""
    };

    function save() {
        // Save blog post
        redirect("/blog", true); // Navigate using wire:navigate
    }

    function cancel() {
        redirect("/blog", true);
    }
}

What wire:navigate Does

When you add wire:navigate to a link, CBWIRE automatically:

  • Intercepts Clicks: Prevents browser from performing full page visits

  • Background Fetching: Requests new page content via AJAX with loading indicator

  • Seamless Swapping: Replaces URL, <title>, and <body> content without refresh

  • Performance Boost: Often achieves 2x faster page loads than traditional navigation

Available Modifiers

The wire:navigate directive supports one modifier:

  • Hover: .hover - Prefetches page content when user hovers over link for 60ms

Example: wire:navigate.hover improves perceived performance but increases server usage.

Here's what happens during navigation:

  1. User clicks a wire:navigate link

  2. Livewire prevents default browser navigation

  3. Loading bar appears at top of page

  4. Page content is fetched in background

  5. New content replaces current page seamlessly

Redirecting with Navigation

Use CBWIRE's redirect() method with navigation enabled:

Persisting Elements Across Pages

Use Alpine's x-persist to maintain elements like audio/video players:

Preserving Scroll Position

Livewire preserves page scroll by default. For specific elements, use wire:scroll:

JavaScript Hooks

Navigation triggers three lifecycle events:

Manual Navigation

Trigger navigation programmatically:

Event Listeners

Handle persistent event listeners properly:

Analytics Integration

Ensure analytics track navigation properly:

Script Handling

Control script execution across navigations:

Progress Bar Customization

Configure the loading indicator:

Custom Loader Example

Create a custom progress indicator:

Persisted elements must be placed outside CBWIRE components, typically in your main layout. Use livewire:navigated instead of DOMContentLoaded for page-specific code.

Was this helpful?