Nesting Components

Livewire supports nesting components. Component nesting can be an extremely powerful technique, but there are a few gotchas worth mentioning up-front:

  1. Nested components CAN accept data parameters from their parents, HOWEVER they are not reactive like props from a Vue component.
  2. Livewire components should NOT be used for extracting Blade snippets into separate files. For these cases, Blade includes or components are preferable.

Here is an example of a nested component called add-user-note from another Livewire component's view.

use Livewire\Component;

class UserDashboard extends Component
{
    public $user;

    public function mount(User $user)
    {
        $this->user = $user;
    }

    public function render()
    {
        return view('livewire.user-dashboard');
    }
}
<div>
    <h2>User Details:</h2>
    Name: {{ $user->name }}
    Email: {{ $user->email }}

    <h2>User Notes:</h2>
    <div>
        @livewire('add-user-note', $user)
    </div>
</div>

Keeping Track Of Components In A Loop

Similar to VueJs, if you render a component inside a loop, Livewire has no way of keeping track of which one is which. To remedy this, livewire offers a special "key" syntax:

<div>
    @foreach ($users as $user)
        @livewire('user-profile', $user, key($user->id))

        <!-- key() using Laravel 7's tag syntax -->
        <livewire:user-profile :user="$user" :key="$user->id">
    @endforeach
</div>

If you are on Laravel 7 or above, you can use the tag syntax.

<div>
    @foreach ($users as $user)
        <livewire:user-profile :user="$user" :key="$user->id">
    @endforeach
</div>
← Previous Topic

Flash Messages

Next Topic →

Loading States

Laravel Intellow Cierra 1043 Labs JR Merritt Trustfactory