Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to insert new text to last caret position? #261

Closed
kunimasu opened this issue Sep 17, 2021 · 1 comment
Closed

How to insert new text to last caret position? #261

kunimasu opened this issue Sep 17, 2021 · 1 comment

Comments

@kunimasu
Copy link

Hi,

Is there any way to insert text such as emoji or something with click other component?
In my case, when I click emoji on emoji UI component, I would like to insert caret position on MDEditor which is before clicking emoji.

Thanks.

@kunimasu
Copy link
Author

kunimasu commented Oct 2, 2021

  const editorRef = React.useRef(null);
  const editorCaretPositionRef = React.useRef(0);

  const updateEditorCaretPositionRef = React.useCallback(() => {

    const el = editorRef.current.textarea;
    let pos = 0;
    if ('selectionStart' in el) {
      pos = el.selectionStart;
    } else if ('selection' in document) {

      el.focus();
      const sel = document.selection.createRange();
      const selLength = document.selection.createRange().text.length;
      sel.moveStart('character', -el.value.length);
      pos = sel.text.length - selLength;

    }
    editorCaretPositionRef.current = pos;

  }, []);

I could get caret by calling above updateEditorCaretPositionRef() from onChange onBlur .
editorRef is set to MDEditor's ref.

I inserted emoji if I selected it on Picker like this.

  const [value, setValue] = React.useState("**Hello world!!!**");

  const handleSelectEmoji = React.useCallback((event, emoji) => {

    const textarea = editorRef.current.textarea;
    const caretPosition = editorCaretPositionRef.current;

    textarea.focus();
    textarea.selectionStart = caretPosition;
    textarea.selectionEnd = caretPosition;

    const text = textarea.value;
    const nextText = text.substring(0, caretPosition) + emoji.emoji + text.substring(caretPosition, textarea.length);
    setValue(nextText);

  }, []);

Thanks.

@kunimasu kunimasu closed this as completed Oct 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant