Best Practices for Laravel Livewire for Beginners

1. Always use the key!

Wherever you use the livewire component you must use the unique key! If you didn’t use the key it would cause the DOM diffing issues!

Use the key() function to define the key for the component!

@livewire("component-name",[], key('name-1'))

When using the nested components, additionally you can add time as a key!

@livewire("component-name",[], key('name-1'.time()))

Using the key in the loop!

Use the [wire:key] property to define the key in the loop.

<div>
   @foreach($datas as $data)
     <div wire:key="{{ $data->id }}">
       {{ $data->content }}
     </div>
   @endforeach
</div>

2. Root element!

A Livewire Component Can Only Have A Single Root Element.

<div> 
     <!-- your code goes here.. --> 
</div>

If you write like this, it will show the error!

<div> 
     <!-- your code goes here.. --> 
</div>

<button wire:click="showSomething()">Click me! </button>

The button will not work here! so you must wrap the content with a div element!

<div>
   <div> 
     <!-- your code goes here.. --> 
   </div>

   <button>Click me! </button>
</div>

See more in livewire Docs…

3. Always pass the DB data via the render() method!

We simply store the DB data in component properties. But it’s not the best practice. you must avoid this for several reasons and the main reason is:

Data stored in public properties is made visible to the front-end JavaScript. Therefore, you SHOULD NOT store sensitive data in them.

This point comes from the Livewire docs…

public $users;
public function mount() {
  $this->users = User::all();
}

Instead of storing database data in component properties. It is generally best practice to use the render() method to pass the data directly to the component view. It is a more safe way to pass the data and it improves performance.

public function render() {
   //get all users
   $users = User::all();

   return view('page-name', compact('users'));
}

4. Trigger browser events!

To dispatch browser events use dispatchBrowserEvents() the method. This allows you to trigger a JS event in the browser from the PHP livewire component. This can be useful for updating the page or triggering an action in third-party JS events!

You don’t need the separate JS code to do that!

//dispatch event
$this->dispatchBrowserEvent('event-name',['data' => 'Message']);

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *