How to insert editable text input to rich text editor

57 Views Asked by At

My solution is work but not what I expected.

Here is my solution

function CreateTemplate() {
  const [formTemplateHTML, setFormTemplateHTML] = useState('')
  const [formTemplateElement, setFormTemplateElement] = useState('')
  const editorRef = useRef(null)

  const handleTemplateSubmit = () => {
    const data = editorRef.current.getData();
    const decodedData = decodeEntities(data);
    
    const cleanedData = decodedData.replace('<p>', '');
    const cleanedData2 = cleanedData.replace('</p>', '');
    
    setFormTemplateElement(data);
    setFormTemplateHTML(cleanedData2);
    console.log(data);
  };

  const insertTextField = (userType) => {
    const editor = editorRef.current
    const text = `<input key="${userType}" />`

    editor.model.change(writer => {
      const insertPosition = editor.model.document.selection.getLastPosition()
      editor.model.insertContent(
        writer.createElement('paragraph'),
        insertPosition,
      )
      editor.model.insertContent(writer.createText(text), insertPosition)
    })
  }

  const decodeEntities = (html) => {
    const textarea = document.createElement('textarea');
    textarea.innerHTML = html;
    return textarea.value;
  };

  return (
    <div className='App'>
      <CKEditor
        editor={ClassicEditor}
        data={formTemplateElement}
        onReady={editor => {
          editorRef.current = editor
        }}
        onChange={(event, editor) => {}}
      />

      <div>
      <button onClick={() => insertTextField('hr')}>Insert Text Field</button>
        <button onClick={handleTemplateSubmit}>Submit</button>
      </div>
      <div>
        <h3>Generated Form:</h3>
        <div dangerouslySetInnerHTML={{__html: formTemplateHTML}} />
      </div>
    </div>
  )
}

From this code, it will generate input element by receiving raw input tag after pressed submit button. But what I want is inserting input element to editor not raw html, is it possible?

Thank you in advance, and sorry if my question seems wired.

What I expected: Image.

SOLVED Just replace with this:

editor.model.change(writer => {
  const viewFragment = editor.data.processor.toView(`<input name=${userType} size = ${size} ></input>`); 
  const modelFragment = editor.data.toModel( viewFragment );  
  editor.model.insertContent( modelFragment, editor.model.document.selection );
})
0

There are 0 best solutions below