Adding mDX component for href

modify a href link in mdx post. so that, internal url uses <Link> component , external link use target="_blank"

Mission

To retain Single web page application, it's a good idea to have external links in your blog open in new tabs with `target="_blank". try this example - hackernews. This way, site remains open in another tab. Implementing this MDX is straightforward just need to create one component and add it to your MDX configuration.

External link example

image loading ...

Internal link example Internal - home blog post

image loading ...
CustomLinks.tsx
import React from "react";
import Link from "next/link";
 
const CustomLink = (props) => {
  const { href, children, ...rest } = props;
  const isExternal =
    href && (href.startsWith("http://") || href.startsWith("https://"));
 
  if (isExternal) {
    return (
      <Link href={href} target="_blank" rel="noopener noreferrer" {...rest}>
        {children}
      </Link>
    );
  }
 
  return <Link href={href}>{children}</Link>;
};
 
export default CustomLink;
mdx-components.tsx
import CustomLink from "@/components/CustomLink";
const components = {
  Image,
  Callout,
  a: CustomLink,
};
 
 
 
export function MDXContent({ code }: MdxProps) {
  const Component = useMDXComponent(code);
  return <Component components={components} />;
}