Search code examples
reactjsmouseeventtrimonblurdraftjs

Trimming Draft.js Editor content with the OnBlur event


In order to trim the content of the Draft.js Editor, the following answer works with the onClick event: Draft.js - How to trim contents

However, I'm unable to make it work with the onBlur event.

In both cases it reaches the method, but only when clicking on the button it performs a trimming of the content.

You can reproduce this problem in the following JSFiddle: https://jsfiddle.net/pnfgrhqz/1/

If you add spaces at the beginning and then click the button, it will trim the content, however, if you do the same and then click out of focus, the trimContent method is also triggered, but the content will not be trimmed.

Any idea what am I missing here?


Solution

  • You have two options. you can either call the trimmer with a setTimeout

      trimOnBlur = () =>{setTimeout(this.trimContent , 0);}
    

    https://jsfiddle.net/bsv3oegr/1/

    or add the onBlur event on the parent div and make it focusable with tabIndex.

     tabIndex="0" onBlur={this.trimContent}
    

    https://jsfiddle.net/8rtcgqkb/