Skip to content

Instantly share code, notes, and snippets.

@cococov
Forked from kachar/Link-Next13.tsx
Created July 20, 2021 02:22
Show Gist options
  • Select an option

  • Save cococov/4e28dc546b43d82bb140fa3c3b8885a2 to your computer and use it in GitHub Desktop.

Select an option

Save cococov/4e28dc546b43d82bb140fa3c3b8885a2 to your computer and use it in GitHub Desktop.
Next.js Link + Material UI Link/Button components bundled with forwardRef
// Plain JS version + prop-types
// Thanks to @IvanAdmaers
import PropTypes from 'prop-types';
import { forwardRef } from 'react';
import NextLink from 'next/link';
import { Button as MuiButton } from '@material-ui/core';
const LinkButton = forwardRef(({ href, as, prefetch, locale, ...props }, ref) => {
return (
<NextLink href={href} as={as} prefetch={prefetch} locale={locale} passHref>
<MuiButton buttonRef={ref} {...props} />
</NextLink>
);
});
LinkButton.displayName = 'LinkButton';
LinkButton.defaultProps = {
href: '#',
prefetch: false,
};
LinkButton.propTypes = {
href: PropTypes.string,
locale: PropTypes.string,
as: PropTypes.string,
prefetch: PropTypes.bool,
};
export default LinkButton;
import React, { forwardRef, Ref } from 'react'
import Link, { LinkProps } from 'next/link'
import { Button, ButtonProps } from '@material-ui/core'
type LinkRef = HTMLAnchorElement | HTMLButtonElement
type NextLinkProps = Omit<ButtonProps, 'href'> &
Pick<LinkProps, 'href' | 'as' | 'prefetch' | 'locale'>
const NextLink = ({ href, as, prefetch, locale, ...props }: LinkProps, ref: Ref<LinkRef>) => (
<Link href={href} as={as} prefetch={prefetch} locale={locale} passHref>
<Button buttonRef={ref} {...props} />
</Link>
)
export default forwardRef<LinkRef, NextLinkProps>(NextLink)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment