-
-
Save cococov/4e28dc546b43d82bb140fa3c3b8885a2 to your computer and use it in GitHub Desktop.
Next.js Link + Material UI Link/Button components bundled with forwardRef
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Plain JS version + prop-types | |
| // Thanks to @IvanAdmaers | |
| import PropTypes from 'prop-types'; | |
| import { forwardRef } from 'react'; | |
| import NextLink from 'next/link'; | |
| import { Link as MuiLink } from '@material-ui/core'; | |
| const Link = forwardRef(({ href, as, prefetch, ...props }, ref) => { | |
| return ( | |
| <NextLink href={href} as={as} prefetch={prefetch} passHref> | |
| <MuiLink ref={ref} {...props} /> | |
| </NextLink> | |
| ); | |
| }); | |
| Link.displayName = 'Link'; | |
| Link.defaultProps = { | |
| href: '#', | |
| prefetch: false, | |
| }; | |
| Link.propTypes = { | |
| href: PropTypes.string, | |
| as: PropTypes.string, | |
| prefetch: PropTypes.bool, | |
| }; | |
| export default Link; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { forwardRef, Ref } from 'react' | |
| import Link, { LinkProps } from 'next/link' | |
| import { Link as MuiLink, LinkProps as MuiLinkProps } from '@material-ui/core' | |
| type LinkRef = HTMLAnchorElement | |
| type NextLinkProps = Omit<MuiLinkProps, 'href' | 'classes'> & | |
| Pick<LinkProps, 'href' | 'as' | 'prefetch'> | |
| const NextLink = ({ href, as, prefetch, ...props }: LinkProps, ref: Ref<LinkRef>) => ( | |
| <Link href={href} as={as} prefetch={prefetch} passHref> | |
| <MuiLink ref={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