Search code examples
laravellaravel-livewire

How to add a class to a Livewire component root tag?


In Laravel Livewire, I have this simple hello component:

<div>
    Hello world
</div>

I would like to add a foobar class to the root div of this component when I use it.

I want the final rendered html to be:

<div class="foobar">
    Hello world
</div>

How can I add this class without editing the component itself?

I tried to call this component by doing <livewire:hello class="foobar" /> and everything works fine... except the class is not there. In fact, it's not limited to class, all attributes disappear.

The rendered html always looks like this:

<div wire:id="jYDWRZST6NCW11Qty9gp">
    Hello world
</div>

Is there something else I should do in order to give this component a class when I use it ?


Solution

  • Unlike blade components, Livewire doesn't support that. You need to add the class inside the component's blade.

    <div class="footer">
        Hello world
    </div>
    
    <livewire:hello />
    

    Alternatively you would need to manually define an attribute inside the component's Class.

    class Hello extends Component
    {
        public $classes
    }
    
    <div class="{{ $classes }}">
        Hello world
    </div>
    
    <livewire:hello classes="footer" />