Draft-js: Select all on focus

Created on 14 Sep 2017  路  9Comments  路  Source: facebook/draft-js

Is it possible to select the whole text when the user focuses the editor?
Can't find an approach on the other issues neither on the documentation.

support

Most helpful comment

Here's what I did.

select() {
  const { editorState } = this.state;
  const currentContent = editorState.getCurrentContent();
  const firstBlock = currentContent.getBlockMap().first();
  const lastBlock = currentContent.getBlockMap().last();
  const firstBlockKey = firstBlock.getKey();
  const lastBlockKey = lastBlock.getKey();
  const lengthOfLastBlock = lastBlock.getLength();

  const selection = new SelectionState({
    anchorKey: firstBlockKey,
    anchorOffset: 0,
    focusKey: lastBlockKey,
    focusOffset: lengthOfLastBlock,
  });

  this.setState({
    editorState: EditorState.acceptSelection(editorState, selection),
  });
}

It works, but I have not tested it thoroughly.

All 9 comments

How do I apply this with draft.js? The draft.js Selection doesn't support selectAllChildren() and applying this to the editors DOM doesn't work.

Did you figure this out @yss14? I'm also trying to do this.

@athomann Unfortunately not.

@yss14 I was able to get the Select all effect by doing

document.execCommand('selectAll', false, null)

after calling a .focus(). Might have to debounce the command.

Here's what I did.

select() {
  const { editorState } = this.state;
  const currentContent = editorState.getCurrentContent();
  const firstBlock = currentContent.getBlockMap().first();
  const lastBlock = currentContent.getBlockMap().last();
  const firstBlockKey = firstBlock.getKey();
  const lastBlockKey = lastBlock.getKey();
  const lengthOfLastBlock = lastBlock.getLength();

  const selection = new SelectionState({
    anchorKey: firstBlockKey,
    anchorOffset: 0,
    focusKey: lastBlockKey,
    focusOffset: lengthOfLastBlock,
  });

  this.setState({
    editorState: EditorState.acceptSelection(editorState, selection),
  });
}

It works, but I have not tested it thoroughly.

@cusxioI I tried but it doesn't work for me :(

CSS user-select: all
Only supported in Chrome and Firefox
More info: https://css-tricks.com/almanac/properties/u/user-select/

@qmind1995

@cusxioI I tried but it doesn't work for me :(

In some cases, you need to use forceSelection instead of acceptSelection

i.e.

this.setState({
  editorState: EditorState.forceSelection(editorState, selection),
});
Was this page helpful?
0 / 5 - 0 ratings