How to get ref to a selected link text

816 Views Asked by At

I have lexical editor, and I want to get reference of a link currently selected/clicked (so that I can position a layover on top of it for the purpose of editing the link) using react?

For example, "link" in the below text.

This is a lexicaljs text with a link that I want to get ref of...

1

There are 1 best solutions below

0
On

If your links are custom DecoratorNodes then you can handle the events in the output React component. I've done this and it works well.

If you're using the default LinkNode then you can try NodeEventPlugin from @lexical/react/LexicalNodeEventPlugin. It lets you attach event listeners to specific node types. You could add a "click" event and access the DOM node from the event object. I'm afraid this is only theoretical since I've only read about it, but the code should look something like this:

<NodeEventPlugin
  eventListener={(e) => {
    const linkElement = e.currentTarget;
    // Open editor UI
  }}
  eventType="click"
  nodeType={LinkNode}
/>

I'm not sure if the event listener approach would also work for selection. If it doesn't, you can try using useLexicalNodeSelection(nodeKey) to detect selection state and then accessing the element directly with editor.getElementByKey(nodeKey).

The Lexical Playground has a version of what you're looking. Try poking around the source code to see how they've done it.