Next.js links and Material-UI links cannot normally be used together.
However, with a little ingenuity, they can be used together.
The following are the requirements for the Link component that we will create using Next.js and Material-UI’s Link.
There are some blogs that show how to use Next.js’s Link and Material-UI’s Button together.
Sample code using Next.js and Material-UI’s Link together
By wrapping Material-UI’s Link with Next.js’s Link, we can use Links together.
In this case, it is necessary to pass a passHref to the Next.js Link.
By having a passHref, Next.js’s Link will pass the href property to its children.
The child Material-UI Link will then receive the href property and create the link.
https://nextjs.org/docs/api-reference/next/link
passHref
– ForcesLink
to send thehref
property to its child. Defaults tofalse
import NextLink from "next/link";
import MuiLink from "@material-ui/core/Link";
<NextLink href="rul" passHref>
<MuiLink>リンク</MuiLink>
</NextLink>
// 新しいタブで開く
<NextLink href="url" passHref>
<MuiLink target="_blank" rel="noopener noreferrer">
リンク
</MuiLink>
</NextLink>
It is also recommended to add rel="noopener noreferrer"
when opening the link in a new tab.
The following security benefits can be obtained.
Make a component
Link is dependent on Next.js and Material-UI.
If you are concerned about dependencies, it is recommended to cut out the link as a component.
By cutting it out as a component, if there is a problem with each dependency, it can be solved by fixing only this component.
import React, { useEffect } from "react";
import NextLink, { LinkProps as NextLinkProps } from "next/link";
import MuiLink from "@material-ui/core/Link";
type LinkProps = {
href: NextLinkProps["href"];
target?: string;
children?: React.ReactNode;
};
export const Link: React.FC<LinkProps> = (props) => (
<NextLink href={props.href} passHref>
<MuiLink target={props.target || "_self"} rel="noopener noreferrer">
{props.children}
</MuiLink>
</NextLink>
);
The Link component that I created can be used in the following way.
By combining the Next.js and Material-UI links into a component, the logic becomes very simple.
import React, { useEffect } from "react";
import Link from "~/src/components/Link";
...
export const User: React.FC<UserProps> = (props) => (
...
<Link
href={'/user/${props.user.id}'}
target="_blank"
>
{props.user.name}
</Link>
...
);
コメント