Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DraftJS triggers content change on focus?

I have an editor on a page and save button. I want save button only to appear if there are changes (since last save). So, when you save, i set this.setState({hasChanges: false}) and in onChange function i set hasChanges to true.

And that's all working fine. The issue is that editor will fire onChange event when editor gain focus (but content is not changed yet). And, that is expected behaviour according to their documentation

The event listeners within the component will observe focus changes and propagate them through onChange as expected, so state and DOM will remain correctly in sync.

Is there some way to know if content has changed inside onChange method, or only selection is changed?

like image 922
Ivan Bajalovic Avatar asked Dec 01 '16 13:12

Ivan Bajalovic


1 Answers

I posted this answer to your question on github earlier today, but I'll add it here as well for future reference:

You're right in that onChange is called every time the editorState changes. And since the editorState holds both the selectionState and the contentState, it will change both when there's a content edit, and when the selection/focus changes.

If you want to know if the change that triggered the onChange method was in the contentState or in the selectionState, you could compare them with their old values:

function onChange(newState) {
  const currentContentState = this.state.editorState.getCurrentContent()
  const newContentState = newState.getCurrentContent()

  if (currentContentState !== newContentState) {
    // There was a change in the content  
  } else {
    // The change was triggered by a change in focus/selection
  }
}

Now, if you know that the change was in the contentState, you can get some more info by calling newState.getLastChangeType(). It should return any of these values (unless you, or some plugin you've added, have created new change types).

like image 93
tobiasandersen Avatar answered Sep 19 '22 11:09

tobiasandersen