Skip to content
This repository has been archived by the owner on Feb 6, 2023. It is now read-only.

Unable to update draft.js content from external Javascript #1044

Closed
MikeSpock opened this issue Mar 1, 2017 · 1 comment
Closed

Unable to update draft.js content from external Javascript #1044

MikeSpock opened this issue Mar 1, 2017 · 1 comment

Comments

@MikeSpock
Copy link

MikeSpock commented Mar 1, 2017

I need to change the editor content from an external javascript, which has access to the Draft.js editor's contenteditable div. Replacing part of the content works ok, but after the focus is set back on the editor, the text is reverted. The reason behind this need is a text spelling corrector browser extension implemented in javascript, which works on most major texteditors, except draft.js (like Facebook's What's on your mind field, chat boxes, etc). I'd like to support draft.js areas as well.

Do you want to request a feature or report a bug?
Neither

What is the current behavior?
It reverts the content to the original version before the replace
https://jsfiddle.net/m6z0xn4r/153/

What is the expected behavior?
There should be some kind of event that would trigger the same as paste when the content is modified from an external script. click / focus / blur / paste / keydown, or something similar

Which versions of Draft.js, and which browser / OS are affected by this issue? Did this work in previous versions of Draft.js?
Most versions

@si13b
Copy link

si13b commented Mar 10, 2017

hi @MikeSpock, my understanding is that this is the intended behaviour. Draft.js is a model-driven editor, i.e. the rendering of the DOM representation is driven entirely from the EditorState object. Any changes to the DOM without also changing the EditorState are discarded. It's a unidirectional relationship, which is the React way of doing things.

The recommended way of doing this would be to use convertFromHTML to create a new ContentState and EditorState object.

e.g.
https://draftjs.org/docs/api-reference-data-conversion.html#content

const sampleMarkup =
  '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
  '<a href="http://www.facebook.com">Example link</a>';

const blocksFromHTML = convertFromHTML(sampleMarkup);
const state = ContentState.createFromBlockArray(
  blocksFromHTML.contentBlocks,
  blocksFromHTML.entityMap
);

this.state = {
  editorState: EditorState.createWithContent(state),
};

You could expose this as a function somehow, or use a messaging system that would allow your external script to notify your component of the new editor content.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants