DEV Community

Saurabh Mahajan
Saurabh Mahajan

Posted on

Livewire Offline Component

Livewire has a feature called Offline State. This can be used to notify the User that they have lost their Internet Connection and are offline. You just need to add the wrap:offline attribute to a div like below:

<div wire:offline>
    You are now offline.
</div>
Enter fullscreen mode Exit fullscreen mode

And this div will only be displayed when user goes offline. In this Tutorial, we will show how to implement this functionality into any existing Livewire Project.

We will create a Livewire Component using below command:

php aritsan make:livewire Offline --inline
Enter fullscreen mode Exit fullscreen mode

This will create a file at app/Http/Livewire/Offline.php.

class Offline extends Component
{
    public function render()
    {
        return <<<'blade'
        <div>
        </div>
        blade;
    }
}
Enter fullscreen mode Exit fullscreen mode

We will then change the render method to return following Output.

<div wire:offline class="fixed top-4 left-1/2">
    <div class="relative -left-1/2 text-red-600 bg-yellow-500 px-4 py-2 font-bold">
        You are currently offline!
    </div>
</div> 

Enter fullscreen mode Exit fullscreen mode

Here we are using Tailwind CSS Classes to fix the Div position at the top of the screen and centered horizontally. See the usage of attribute wire:offline which makes sure that this will only display when the User is offline.

Now you just need to include this component in the Layout like below:

@livewire('offline')
Enter fullscreen mode Exit fullscreen mode

And that’s it, any time user goes offline, the warning will be displayed to the user like below:

Screenshot

Top comments (0)