How to clear input field in Draft-js
Asked Answered
F

4

15

None of the demos that I've seen for Draft-js (by Facebook, built on React) show how to clear the input field after submit. For example, see this code pen linked to from awesome-draft-js where the value you submit remains in the input field after submit. There's also no function in the api that seems designed to do it. What I've done to achieve that is to create a new empty state on button submission like this

onSubmit(){
this.setState({
   editorState: EditorState.createEmpty(),
})
}

However, since I create an empty state in the constructor when the editor is loaded like this

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

I'm worried that I might not be doing it in the right way i.e. the previous state object might become a memory leak. Question: what is the intended way to reset the state in the above situation (i.e. button submit)

Forewing answered 26/5, 2016 at 14:28 Comment(1)
I created an example of what you are after and it seems to work okay. I've filled the draft-js editor with some default content on mount. Clicking the submit button empties the state using the EditorState.createEmpty() function. Seems fine. webpackbin.com/NkNbdZlXZEncratia
P
34

It is NOT recommended to use EditorState.createEmpty() to clear the state of the editor -- you should only use createEmpty on initialization.

The proper way to reset content of the editor:

import { EditorState, ContentState } from 'draft-js';

const editorState = EditorState.push(this.state.editorState, ContentState.createFromText(''));
this.setState({ editorState });

@source: https://github.com/draft-js-plugins/draft-js-plugins/blob/master/FAQ.md

Pulpiteer answered 19/8, 2016 at 0:23 Comment(5)
You may want to pass the third parameter too. EditorState.push(editorState, ContentState.createFromText(''), 'remove-range')Gossipry
any explanations why it's not recommended to use EditorState.createEmpty()? It works good for me.Sum
@Sum it might induce getEditorState is not a function error someday.Circle
This answer is not correct. This answer indeed messes with the cursor on the next input. @Fabian's answer should be selected as the correct answerPrado
cursor bug will happen with this solution, but to fix that add this line editorRef.current.focus() after update the state.Crushing
J
9

@Vikram Mevasiya's solution does not clear block list styles correctly

@Sahil's solution messes with the cursor on the next input

I found that this is the only working solution:

// https://github.com/jpuri/draftjs-utils/blob/master/js/block.js
const removeSelectedBlocksStyle = (editorState)  => {
    const newContentState = RichUtils.tryToRemoveBlockStyle(editorState);
    if (newContentState) {
        return EditorState.push(editorState, newContentState, 'change-block-type');
    }
    return editorState;
}

// https://github.com/jpuri/draftjs-utils/blob/master/js/block.js
export const getResetEditorState = (editorState) => {
    const blocks = editorState
        .getCurrentContent()
        .getBlockMap()
        .toList();
    const updatedSelection = editorState.getSelection().merge({
        anchorKey: blocks.first().get('key'),
        anchorOffset: 0,
        focusKey: blocks.last().get('key'),
        focusOffset: blocks.last().getLength(),
    });
    const newContentState = Modifier.removeRange(
        editorState.getCurrentContent(),
        updatedSelection,
        'forward'
    );

    const newState = EditorState.push(editorState, newContentState, 'remove-range');
    return removeSelectedBlocksStyle(newState)
}

Its a combination of two helper functions provided by https://github.com/jpuri/draftjs-utils . Didn't want to npm install the entire package for this. It resets the cursor state but keeps the block list styling. This is removed by applying removeSelectedBlocksStyle() I just can't belive how a library this mature doesn't offer a one-line reset feature.

Jacal answered 11/11, 2020 at 16:49 Comment(2)
Some more context here: github.com/facebook/draft-js/issues/1630Poach
This answer is the winner.Ruy
S
3

Try this

    let editorState = this.state.editorState
    let contentState = editorState.getCurrentContent()
    const firstBlock = contentState.getFirstBlock()
    const lastBlock = contentState.getLastBlock()
    const allSelected = new SelectionState({
        anchorKey: firstBlock.getKey(),
        anchorOffset: 1,
        focusKey: lastBlock.getKey(),
        focusOffset: lastBlock.getLength(),
        hasFocus: true
    })
    contentState = Modifier.removeRange(contentState, allSelected, 'backward')
    editorState = EditorState.push(editorState, contentState, 'remove-range')
    editorState = EditorState.forceSelection(contentState, contentState.getSelectionAfter())
    this.setState({editorState})
Simp answered 21/2, 2019 at 6:52 Comment(0)
A
1
const content = {
  entityMap: {},
  blocks:[
    { 
      key: "637gr",
      text: "",
      type:"unstyled",
      depth:0,
      inlineStyleRanges:[],
      entityRanges: [],
      data: {}
    }
  ]
};
  1. const [editorContent, setEditorContent] = useState(content);

  2. <Editor contentState={editorContent} />

contentState prop does the trick after saving you can use setEditorContent to reset the editor

setEditorContent(content)
Anomaly answered 16/7, 2021 at 23:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.