5

small component looks like so:

// @flow
import ReactMarkdown from "react-markdown";
import type { Node } from "react";

function LinkRenderer(props: any) {
  return (
    <a href={props.href} target="_blank" rel="noreferrer">
      {props.children}
    </a>
  );
}

type Props = {
  children: Node,
};

const MarkdownRenderer = ({ children }: Props) => {
  return (
    <ReactMarkdown components={{ link: LinkRenderer }}>
      {children}
    </ReactMarkdown>
  );
};

Can anyone suggest why my links aren't opening in a new tab when using this component?

Implementing the component like so in other components:

<MarkdownRenderer>{value}</MarkdownRenderer>

cts
  • 908
  • 1
  • 9
  • 30

2 Answers2

9

You need to update the prop from the 'link' to 'a' to achieve that.

  <ReactMarkdown components={{ a: LinkRenderer}}>
      {children}
  </ReactMarkdown>

Please find the sandbox link

Also if you are not doing too much customization and added the custom renderer just for opening a link in a new tab. You can make use of 'linkTarget' prop and set it to '_blank'

wolf_codes
  • 254
  • 2
  • 11
6

You can use linkTarget now to make your link open in a new tab:

<ReactMarkdown linkTarget="_blank" children={...} />
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 13 '23 at 16:55