Draft-js: How to check if cursor is inside element?

Created on 28 Aug 2019  路  5Comments  路  Source: facebook/draft-js

So, instead of having a link and unlink button, I would prefer to have a single link button that when pressed, it first checks if the cursor is within an anchor tag. If it is, it should remove it, if is not, it should create a new link. How would I implement this using draft-js or draftjs-utils?

Most helpful comment

@brielov, i found this:

const isLink = () => {
  const contentState = editorState.getCurrentContent();
    const startKey = editorState.getSelection().getStartKey();
    const startOffset = editorState.getSelection().getStartOffset();
    const currentBlock = contentState.getBlockForKey(startKey);
    const entityKey = currentBlock.getEntityAt(startOffset);
    return (
      entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK'
    );
}

const setLink = () => {
  ...
}

const unLink = () => {
  ...
}

const onToggleLink = () => {
  if (isLink) {
    unlink()
  } else {
    setLink()
  }
}

All 5 comments

Nobody?

@brielov have you tried getEntity? https://draftjs.org/docs/api-reference-character-metadata.html#getentity

I haven't used it personally, but I use getStyle to check whether an inline selection is applied at the cursor location. I assume getEntity should work the same for your links

@jkhaui , hello.
i cant use getStyle or getEntity to selection directly (let selection = EditorState.getSelection()). how can i get character or list of characters from current cursor/selection to be able to use getStyle or getEntity? thanks in advance.

@brielov, i found this:

const isLink = () => {
  const contentState = editorState.getCurrentContent();
    const startKey = editorState.getSelection().getStartKey();
    const startOffset = editorState.getSelection().getStartOffset();
    const currentBlock = contentState.getBlockForKey(startKey);
    const entityKey = currentBlock.getEntityAt(startOffset);
    return (
      entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK'
    );
}

const setLink = () => {
  ...
}

const unLink = () => {
  ...
}

const onToggleLink = () => {
  if (isLink) {
    unlink()
  } else {
    setLink()
  }
}

@ZefirTheFear Thanks for the response, I'm not currently working with draft anymore but I have an upcoming project and I'll be making use of your snippet to try it out. Cheers 馃嵒

Was this page helpful?
0 / 5 - 0 ratings