Search code examples
htmllaravel-livewire

Checkbox flicker with livewire


I needed a way to hide and show columns in a table using livewire so I created a variable to hold the "true" or "false" value. This is what I have in my blade

<input  value="showRate" type="checkbox" wire:click="$set('showRate', {{ $showRate ? 'false' : 'true' }})" >Rate

And in mount I simply initialize the value to true

public function mount(){
        $this->showRate = true;
    }

In browser everything works as expected, but the checkbox when switched appears for a few mili-seconds then disappears. This is part of my table view.

              @if($showRate)
                     <th wire:click="sortBy('SFM_rate')" style="cursor: pointer;" class="px-4 py-2">SFM Rate @include('partials.sort-icon',['field'=>'SFM_rate'])</th>
              @endif

I am pretty sure there is another way to make this more efficient but this was the first solution that popped into my mind. If you have any suggestions feel free to teach me a better solution.


Solution

  • The flickering appears to be the result of a conflict of state ownership between the browser and Livewire.

    If you alter your checkbox to the following, the flickering stops:

    <input
        wire:click="$set('showRate', {{ $showRate ? 'false' : 'true' }})"
        type="checkbox"
        value="showRate"
        @if ($showRate) checked="checked" @endif>
    
        Rate
    

    Alternatively Livewire provides a helper for toggling the value of boolean properties:

    <input wire:click="$toggle('showRate')"
        type="checkbox"
        value="showRate" />
    
        Rate