1

I am using AutoLinkNode and LinkNode from '@lexical/link'.

How can I set target="_blank" to be default on newly created links? Do I need to override the LinkNode class or is there an easier way?

nerdess
  • 10,051
  • 10
  • 45
  • 55
  • You can always pass in pre-defined default attributes with `target` set to `_blank`. If that is not an option - overwrite class itself. – Justinas Jun 27 '23 at 07:34
  • 1
    @Justinas thy for you response, can you quickly post a code example? – nerdess Jun 28 '23 at 09:26

2 Answers2

0

You could extend the AutoLinkNode and LinkNode, but the easiest solution is registering a node transform listener like this example that I prepared. Please see: https://codesandbox.io/s/loving-faraday-7l9vqy?file=/src/plugins/AutoLinkPlugin.js

In short, that would be doing something like for the LinkNode:

import { useEffect } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { LinkNode } from "@lexical/link";

export default function LinkNodePlugin() {
  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    if (!editor) return;
    const removeNodeListener = editor.registerNodeTransform(
      LinkNode,
      (node) => {
        if (!node) return;

        const dom = editor.getElementByKey(node.__key);
        if (!dom) return;
        dom.setAttribute("target", "_blank");
      }
    );
    return () => removeNodeListener();
  }, [editor]);
  return null;
}

And something like that for the AutoLinkNode:

  const [editor] = useLexicalComposerContext();

  useEffect(() => {
    if (!editor) return;
    const removeNodeListener = editor.registerNodeTransform(
      AutoLinkNode,
      (node) => {
        if (!node) return;
        const dom = editor.getElementByKey(node.__key);
        if (!dom) return;
        dom.setAttribute("target", "_blank");
      }
    );
    return () => removeNodeListener();
  }, [editor]);
Mila A
  • 375
  • 2
  • 10
0

You can directly add LinkAttributes to your AutoLinkNode, LinkNode

    const linkAttributes = {
        target: "_blank",
        rel: "noopener noreferrer",
    };

And simply add the linkAttributes,

      editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
        url: "https://",
        ...linkAttributes,
      });

For more information,Module: @lexical/link