How to clear input field in Draft-js
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})
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
@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.