LoginSignup
1
0

More than 1 year has passed since last update.

Next.js とmui/Material-UIのLinkを併用する

Posted at

Next.js とmui/Material-UIのLinkを併用する

Next.jsとmuiのLinkが上手くいかない

import NextLink, { LinkProps } from 'next/link'
import { Link as MuiLink } from '@mui/material'

import React, { ReactNode } from 'react'

type Props = {
  linkProps: LinkProps
  children?: ReactNode
  target?: string
  rel?: string
}

const Link: React.FC<Props> = ({ linkProps, children, target, rel }) => {
  return (
    <NextLink href={linkProps.href} passHref>
      <MuiLink
        target={target}
        rel={rel}
      >
        {children}
      </MuiLink>
    </NextLink>
  )
}

export default Link

このようにNextLinkの子要素としてMuiLinkをしようとすると下記のようなエラーが発生すると思います。
Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>.
このエラーはaタグの子要素としてaタグがあるのダメだよっていうエラーです。

なぜそうなるかというとnext/linkがいつかのアップデートにより子要素をaタグでラップするといった仕様になったからなのです!

そのため、現在ではこの書き方に追加して、legacyBehaviorプロパティを追加してあげる必要があります。next公式

Next.jsとmuiのLinkが上手くいく

import NextLink, { LinkProps } from 'next/link'
import { Link as MuiLink } from '@mui/material'

import React, { ReactNode } from 'react'

type Props = {
  linkProps: LinkProps
  children?: ReactNode
  target?: string
  rel?: string
}

const Link: React.FC<Props> = ({ linkProps, children, target, rel }) => {
  return (
-    <NextLink href={linkProps.href} passHref>
+    <NextLink href={linkProps.href} passHref legacyBehavior>
      <MuiLink
        underline='none'
        target={target}
        rel={rel}
      >
        {children}
      </MuiLink>
    </NextLink>
  )
}

export default Link

おまけ

このlinkコンポーネントの使用方法

 <Link linkProps={{ href: '/' }}>ホーム</Link>
//別タブでの表示
 <Link linkProps={{ href: '/' }} target='_blank' rel='noopener noreferrer'>ホーム</Link>

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0