Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear input field in Draft-js

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)

like image 956
Leahcim Avatar asked May 26 '16 14:05

Leahcim


Video Answer


1 Answers

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})
like image 81
Vikram Mevasiya Avatar answered Sep 23 '22 17:09

Vikram Mevasiya