I’ve got a Blade file like this:
<a href="{{ $url }}" class="{{ $wrapperClass }}">
<p class="{{ $paraClass }}">{{ $title }}</p>
</a>
And call it like this:
<x-mycomponent
url="{{ $book->url }}"
title={{ $book->title }}
wrapper-class=""
para-class = ""
/>
Works great, but whenever I want to add a variable to the component, I need to add this to each file where I call this component.
How can I write it without having to specify all variables and without having to use isset()
or {{ $myvar ?? '' }}
in Blade? like this:
<x-mycomponent
url="{{ $book->url }}"
title={{ $book->title }}
/>
>Solution :
You can assign default values for your properties like the below’s peace of code:
@props([
"product" => null
])
<a href="#">{{ $product }}</a>
and then, you can call your component in both these ways:
<x-mycomponent />
<x-mycomponent product="$product" />
Note: @props
is a Blade directive that allows you to pass data from a parent component to a child component.