Skip to content

Instantly share code, notes, and snippets.

@tomcask
Created January 10, 2017 16:52
Show Gist options
  • Save tomcask/6040f6695712df5d31645e48bda3fc2b to your computer and use it in GitHub Desktop.
Save tomcask/6040f6695712df5d31645e48bda3fc2b to your computer and use it in GitHub Desktop.
Example of force selection in draftjs
const getEditorState = this.props.store.getItem('getEditorState');
const setEditorState = this.props.store.getItem('setEditorState');
const selection = this.props.store.getItem('lastSelection');
const editorState = getEditorState();
const updateSelection = new SelectionState({
anchorKey: selection.anchorKey,
anchorOffset: selection.anchorOffset,
focusKey: selection.anchorKey,
focusOffset: selection.focusOffset,
isBackward: false,
});
let newEditorState = EditorState.acceptSelection(
editorState,
updateSelection
);
newEditorState = EditorState.forceSelection(newEditorState, newEditorState.getSelection());
setEditorState(newEditorState)
@lvdang
Copy link

lvdang commented Nov 13, 2019

What is the difference of using acceptSelection vs forceSelection?

@tomcask
Copy link
Author

tomcask commented Nov 13, 2019

Forceselection
Returns a new EditorState object with the specified SelectionState applied, forcing the selection to be rendered.

This is useful when the selection should be manually rendered in the correct location to maintain control of the rendered output.

AcceptSelection the same but without requiring the selection to be rendered.

@lvdang
Copy link

lvdang commented Nov 13, 2019

Could you just pass in newSelectionState without having to create a new EditorState from acceptSelection()?

e.g.
newEditorState = EditorState.forceSelection(newEditorState, updateSelection);

@tomcask
Copy link
Author

tomcask commented Nov 13, 2019

I'm sorry but I haven't used draftjs in a while, you'd have to do a test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment