Created
September 29, 2020 11:44
-
-
Save brokenthorn/67d8b5bee2f2f048fae9e56a67d5e524 to your computer and use it in GitHub Desktop.
Partially converted TSX version of Material UI wraper for Next.js Link component
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, { RefObject } from 'react' | |
import { useRouter } from 'next/router' | |
import clsx from 'clsx' | |
import MuiLink, { LinkProps as MuiLinkProps } from '@material-ui/core/Link' | |
import NextLink, { LinkProps } from 'next/link' | |
const NextComposed = React.forwardRef(function NextComposed( | |
props: LinkProps, | |
ref: RefObject<HTMLAnchorElement> | |
) { | |
const { as, href, ...other } = props | |
return ( | |
<NextLink href={href} as={as}> | |
<a ref={ref} {...other} /> | |
</NextLink> | |
) | |
}) | |
// A styled version of the Next.js Link component. | |
function Link(props: any) { | |
// TODO: Find proper type declaration to use for Link(props: any). | |
const { | |
href, | |
activeClassName = 'active', | |
className: classNameProps, | |
innerRef, | |
naked, | |
...other | |
} = props | |
const router = useRouter() | |
const pathname = typeof href === 'string' ? href : href.pathname | |
const className = clsx(classNameProps, { | |
[activeClassName]: router.pathname === pathname && activeClassName, | |
}) | |
if (naked) { | |
return ( | |
<NextComposed | |
className={className} | |
ref={innerRef} | |
href={href} | |
{...other} | |
/> | |
) | |
} | |
return ( | |
<MuiLink | |
component={NextComposed} | |
className={className} | |
ref={innerRef} | |
href={href} | |
{...other} | |
/> | |
) | |
} | |
export default React.forwardRef( | |
(props: MuiLinkProps, ref: RefObject<HTMLAnchorElement>) => ( | |
<Link {...props} innerRef={ref} /> | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment