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