Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper way to wire up Trix editor with Livewire?

When wiring together Trix editor content with Livewire, I am stumbling into problems. I believe that the issue is that when Livewire receives content from Trix, the content is swapped out and Trix becomes disabled. Is there a better way?

What I have done, that works, is as follows. At the moment, the page is the redirected to itself in order to reboot Trix (defeating the whole point of Livewire, but it's being used for other things too).

<div>
  <input
      id="newCommentTextTrixContent"
      type="hidden"
      wire:model="newCommentText"
  >

  <trix-editor
      id="newCommentTextTrixEditor"
      input="newCommentTextTrixContent"
  ></trix-editor>


  <button wire:click="addComment(document.getElementById('newCommentTextTrixEditor').innerHTML)">Add Comment</button>
</div>

I have tried

  • wire:model on the hidden input -- nothing happens
  • x-on:trix-change="$set('comment', $event.target.innerHTML) -- this works, but Trix goes grey and ceases to work after the first keypress (reboot problem?)

I'm sure something like the latter is better, but with Trix somehow being rebooted each time. It all seems a bit messy - so the question is, what's the right way to do this?

like image 650
Kurucu Avatar asked Mar 05 '20 06:03

Kurucu


1 Answers

I got it working. With up to date Livewire and Alpine installations, the code is roughly as follows.

    <div wire:ignore>
        <trix-editor
            class="formatted-content"
            x-data
            x-on:trix-change="$dispatch('input', event.target.value)"
            x-ref="trix"
            wire:model.debounce.60s="newCommentText"
            wire:key="uniqueKey"
        ></trix-editor>
    </div>

Why does this work?

  • You need wire:ignore on the parent node, because Trix inserts the toolbar above the text area. wire:ignore stops Livewire from worrying about it and therefore not removing it or messing with it on the next cycle.
  • You need a wire:key because the DOM moves around a bit, and this helps Livewire to keep track of it.
  • I propose the long debounce, which is a hack as the .lazy modifier doesn't work well with text. Also, waiting for Ajax on each key press is painful.
  • The alpine event ensures that Trix events (like bold, italics etc) are still fired

That's it. I use this above to repetitively submit comments onto the end of a comment stream, and everything seems to work fine. Good luck!

Note, I also have CKEditor working similarly, as described here.

like image 193
Kurucu Avatar answered Oct 04 '22 16:10

Kurucu