Search code examples
entitydraftjs

Remove / clear all entities from a contentState


I'm trying to remove all entities from a contentState.

What would be the prefered way to do that?


Solution

  • Not sure what the canonical way is, but I've been able to do it by using Modifier.applyEntity(): https://draftjs.org/docs/api-reference-modifier#applyentity.

    You basically need to loop through all the blocks, and use that method on the entire range of text in each block. So something like this:

    import {Modifier, SelectionState} from 'draft-js';
    function clearEntityRanges(contentState){
      contentState.getBlockMap().forEach(block => {
        const blockKey = block.getKey();
        const blockText = block.getText();
        // You need to create a selection for entire length of text in the block
        const selection = SelectionState.createEmpty(blockKey);
        const updatedSelection = selection.merge({
          //anchorOffset is the start of the block
          anchorOffset: 0,
          // focustOffset is the end
          focusOffset: blockText.length
        })
        Modifier.applyEntity(contentState, updatedSelection, null);
      });
      return contentState
    }