TAKEO

TAKEO

リンクを新規タブで開くようにする next-mdx-remote

リンクを新規タブで開きたい!

htmlのaタグでは次のようにしますよね。

Copied!!
<a target="_blank">hoge hoge</a>

本記事ではnext-mdx-remoteを使っている場合に、マークダウン内のリンクを新規タブで開くようにする方法について紹介します。

方法

  1. カスタムコンポーネントを作る

    components/customlink.js
    Copied!!
    import Link from "next/link";
    
    export default function CustomLink(props){
        const href = props.href;
        // 内部リンクかどうか
        const isInternalLink = href && (href.startsWith('/'));
    
        if (isInternalLink) {
        return (
            <Link href={href}>
            {props.children}
            </Link>
        );
        }
    
        return <a target="_blank" {...props} />;
    };
    
    
  2. keyをaとしてcomponentsに登録する

    Copied!!
    const components = {
      a: (props) => <CustomLink {...props} />,
    };
    
    pages/example.js
    Copied!!
    import { MDXRemote } from 'next-mdx-remote'
    import CustomLink from '../../components/customlink'
    
    const components = {
        a: (props) => (
            <CustomLink {...props}/>
        )
    };
    
    export default function TestPage({ source }) {
        return (
            <MDXRemote {...source} components={components} />
        )
    }
    
    export async function getStaticProps() {
        // markdown形式のリンク
        const source = '[google](https://www.google.com)'
        const mdxSource = await serialize(source)
        return { props: { source: mdxSource } }
    }
    

所感

  • 外部リンクは強制的に新規タブを開くようになりそう

関連記事