Search code examples
javascriptreactjshyperlinkreact-markdown

React Markdown links dont open in a new tab despite using target="_blank"


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>


Solution

  • 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'