Moving cursor in react slate-editor

5.3k views Asked by At

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 ?

3

There are 3 answers

0
Denis L On

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);
0
angelfire529 On

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

0
Tasos Tsournos On

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);