basecamp / trix

A rich text editor for everyday writing
https://trix-editor.org/
MIT License
18.87k stars 1.11k forks source link

Dynamically added trix-editor not picking up it's input content #504

Closed randohinn closed 6 years ago

randohinn commented 6 years ago

I'm using Stimulusjs to add an input, and a attached trix-editor to the page, replacing the text, that was there before. The input gets the correct id and value, but the editor created is empty...

Steps to Reproduce
const content = this.areaTarget.innerHTML;
this.areaTarget.classList.add("border-blue");
this.areaTarget.innerHTML ='<input id="'+this.areaTarget.id+'" value="'+content+'" type="hidden"><trix-editor input="'+this.areaTarget.id+'"></trix-editor>';

The elements added look like this:

<div id="154d366a-5375-41e9-a32c-a7c37da19dc1" class="border border-grey trix-content border-blue" data-controller="text-area" data-action="click->text-area#edit" data-target="text-area.area">
<input id="154d366a-5375-41e9-a32c-a7c37da19dc1" value="Lorem ipsum dolor sit amet..." type="hidden">
<trix-toolbar id="trix-toolbar-1"></trix-toolbar>
<trix-editor input="154d366a-5375-41e9-a32c-a7c37da19dc1" trix-id="1" toolbar="trix-toolbar-1" contenteditable=""></trix-editor>
</div>
Details
javan commented 6 years ago

Your <input> has the same ID as the parent <div> element, which is technically invalid, and results in Trix finding the wrong element because it uses document.getElementById() under the hood. Try giving it a distinct ID:

const content = this.areaTarget.innerHTML;
const inputId = "input-" + this.areaTarget.id;
this.areaTarget.classList.add("border-blue");
this.areaTarget.innerHTML = '<input id="'+inputId+'" value="'+content+'" type="hidden"><trix-editor input="'+inputId+'"></trix-editor>';
randohinn commented 6 years ago

🤦‍♂️ Of course, thanks!