How to enable Ctrl + Z when dynamically changing input text using React?

I am trying to create a simple React markdown editor .

editor

The component is fully controlled. The problem is this: if the user selects abc in the text box and presses the B button, I need to call onchange() with **abc** . I need to surround the text with these asterisks.

This difference between what I pass on onchange() and what the user actually typed in makes the textarea history become inconsistent. Ctrl + Z no longer works.

Demo [EDIT: A fix is ​​implemented in this demo. This is not the way it was when I asked the question]

How can I call onchange() in response to arbitrary text and maintain a consistent combination of Ctrl + Z?

+7
javascript reactjs
source share
1 answer

I haven't solved the problem, but maybe this is the best I can do without reinstalling the story as @Rishat mentioned (if I'm wrong, let me know).

Thanks to this answer , I understood this command:

 document.execCommand("insertText", false, text); 

This basically inserts text at the current focused input at the current caret position (why don't you pass the input as a parameter). And, of course, this function updates the history accordingly.

If I wanted to, I could coordinate each insert (e.g. ** mentioned in the question) so that everything was in the story. However, this would be too difficult because each markdown team has a different behavior. That would be too complicated.

Decision:

The following code should be included in componentDidUpdate and should only be executed after the text has been changed programmatically :

 // In order to minimize the history problem with inputs, we're doing some tricks: // - Set focus on the textarea // - Set the value back to its previous value. // - Select the whole text (that the problem) // - Insert the new value this.refs.textarea.focus(); this.refs.textarea.value = previousText; setSelection(this.refs.textarea, 0, previousText.length); document.execCommand("insertText", false, text); 

the effect

Ctrl + Z works fine, but if you keep coming back until the input time has been changed programmatically, it will select all the text. I mean, the story is saved, but at the cost of clutter with the choice if you return enough. I believe this is good enough, better than reimplementing the input story.

Demo

+1
source share

All Articles