4

I'm trying to move the cursor in react slate-editor.

I tried to do it in 2 ways.

First:

// This code saving key in offset in variables
const nativeSelection = this.getSelectedText();
const nativeRange = nativeSelection.getRangeAt(0);
    const range = findRange(nativeRange, this.editor);
const offset = nativeRange.endOffset;
const key = range.anchor.key;

// OnChange is triggered by running the next line and cursor moves back
this.editor.blur();

// Trying to move to the cursor
this.editor.moveTo(key, offset);

Second:

const nativeSelection = this.getSelectedText();
const nativeRange = nativeSelection.getRangeAt(0);
const range = findRange(nativeRange, this.editor);
const clonedRange = _.cloneDeep(range);

// OnChange is triggered by running the next line and cursor moves back
this.editor.blur();

// Trying to move the cursor
this.editor.select(clonedRange);

Unfortunately, select and moveTo doesn't seem to affect the cursor position. Can someone assist ?

ohadinho
  • 6,894
  • 16
  • 71
  • 124

3 Answers3

7

Try using Transform.select method combining with a location point

Put cursor after 3rd letter

Transforms.select(editor, {path: [0, 0], offset: 3});

Move to the very end

Transforms.select(editor, Editor.end(editor, []));

You also can try the method Transforms.move. Move cursor after 5th word:

Transforms.move(editor, {distance: 5, unit: 'word'});

Or end the line:

Transforms.move(editor, {distance: 1, unit: 'line'});

It is also worth noting that in my case I had to run the transformation in a setTimeout after setting the editor value. Example:

setValue(content);
setTimeout(() => {
   Transforms.move(editor, {distance: 1, unit: 'line'});
}, 20);
Denis L
  • 3,209
  • 1
  • 25
  • 37
0

Or more explicitly:

const lastNode = editor.children[editor.children.length - 1];
const lastNodePath = ReactEditor.findPath(editor, lastNode);
const endPoint = Editor.end(editor, lastNodePath);

Transforms.select(editor, endPoint);
Tasos Tsournos
  • 314
  • 2
  • 9
-1

If you're using the latest version of Slate.js you can use Transforms.move(editor, { options })