How to autofocus atomic block in draft js

Viewed 29

Suppose I inserted a new custom block like

const insertBlock = () => {
    const contentState = editorState.getCurrentContent();

    const contentStateWithEntity = contentState.createEntity(
      "EDITORELEMENT",
      "MUTABLE",
      {
        a: "b"
      }
    );

    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
    const newEditorState = EditorState.set(editorState, {
      currentContent: contentStateWithEntity
    });

    setEditorState(
      AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, "text")
    );
  };
const EditorElement: React.FC = (props: any) => {
  return (
    <div className="EditorElement">
      <EditorBlock {...props} />
    </div>
  );
};

How do I auto-focus this new block right after inserting it? Tried many solution using forceSelection, focus but they didn't work

1 Answers

I solved this problem. Carefully read selection state spec. So, basically, we need anchor (or start) and focus (or end). Since I want only to move my caret into the block, 0 values are okay for me. Then, I need an offsetKey of the same block I want to select. In my case, I did it by taking a block prop from my component EditorElement. So, the whole useEffect hook looks like this.

const { block, contentState } = props;
  useEffect(() => {
    const key = block.getKey();

    const selection = SelectionState.createEmpty(key).merge({
      anchorKey: key,
      anchorOffset: 0,
      focusKey: key,
      focusOffset: 0
    });

    const { setEditorState } = props.blockProps;
    setEditorState((prev: EditorState) =>
      EditorState.forceSelection(prev, selection)
    );
  }, []);
Related