Nesting Components
Livewire supports nesting components. Component nesting can be an extremely powerful technique, but there are a few gotchas worth mentioning up-front:
- Nested components CAN accept data parameters from their parents, HOWEVER they are not reactive like props from a Vue component.
- 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.
1use Livewire\Component; 2 3class UserDashboard extends Component 4{ 5 public $user; 6 7 public function mount(User $user) 8 { 9 $this->user = $user;10 }11 12 public function render()13 {14 return view('livewire.user-dashboard');15 }16}
1<div> 2 <h2>User Details:</h2> 3 Name: {{ $user->name }} 4 Email: {{ $user->email }} 5 6 <h2>User Notes:</h2> 7 <div> 8 @livewire('add-user-note', ['user' => $user]) 9 </div>10</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:
1<div>2 @foreach ($users as $user)3 @livewire('user-profile', ['user' => $user], key($user->id))4 @endforeach5</div>
If you are on Laravel 7 or above, you can use the tag syntax.
1<div>2 @foreach ($users as $user)3 <livewire:user-profile :user="$user" :key="$user->id">4 @endforeach5</div>
Sibling Components in a Loop
In some situations, you may find the need to have sibling components inside of a loop, this situation requires additional consideration for the key
value.
Each component will need its own unique key
, but using the method above will lead to both sibling components having the same key, which will cause unforeseen issues. To combat this, you could ensure that each key
is unique by prefixing it with the component name, for example:
1<!-- user-profile component --> 2<div> 3 // Bad 4 <livewire:user-profile-additional-component :user="$user" :key="$user->id"> 5 <livewire:user-profile-some-related-component :user="$user" :key="$user->id"> 6 7 // Good 8 <livewire:user-profile-additional-component :user="$user" :key="'user-profile-additional-component-'.$user->id"> 9 <livewire:user-profile-some-related-component :user="$user" :key="'user-profile-some-related-component-'.$user->id">10</div>