Back to Course |
Livewire 3 From Scratch: Practical Course

Nested Components and Their "Bug"

You can include one component into another component in Livewire. Let's imagine we have one component for listing comments, inside it, we have a component to show a comment. So each comment is a Livewire component. There is one crucial aspect to know when adding a nested component.

nested comments component


So we have a Livewire component, CommentsList, where we get the comments, order them and do other needed tasks. Then in the Blade, we show them like so:

resources/views/livewire/comments-list.blade.php:

<div>
@foreach ($comments as $comment)
<livewire:comment-show :$comment wire:key="{{ $comment->id }}" />
@endforeach
</div>

Nothing particular here in the Blade file. The only thing Livewire says to add a wire:key when looping data in @foreach. In the CommentsList component, we call another Livewire component, CommentShow, and pass the comment.

In the CommentShow, we assign everything to public properties and show the comment.

resources/views/livewire/comment-show.blade.php:

<div class="mb-4 mt-4 ml-{{ $level*4 ?? '0' }}">
[ {{ $comment->rating }} ] <span class="font-semibold">{{ $user->name }}
[{{ $comment->created_at->format('Y-m-d H:i') }}]:</span>
{{ $comment->comment_text }}
@auth
<a wire:click="vote(1)" href="#" class="underline">+1</a>
<a wire:click="vote(-1)" href="#" class="underline">-1</a>
@endauth
 
@foreach ($comment->comments->sortByDesc('rating') as $comment)
<
@endforeach
</div>

Again, the most important aspect here is to add :key when rendering a child component.

Adding keys is necessary to avoid getting into issues that will be very hard to diagnose.


Course Conclusion

And that's it for this course. Now you can go and practice more with Livewire!

The code for this course is available in this GitHub repository.