Created
July 22, 2021 22:15
-
-
Save ItsWendell/bcaa87382d1cd152d5d1d7d6911c341e to your computer and use it in GitHub Desktop.
withNextLink - Higher Order Component for Linkable components to support Next.JS Routing / Links
This file contains 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 from "react"; | |
import NextLink, { LinkProps } from "next/link"; | |
/** | |
* Higher Order Component to turn any component with a href into a component that supports `next/link`. | |
* | |
* Pass the component props like this: | |
* @example const Button = withNextLink<ButtonProps>(MuiButton); | |
* TODO: Look into forwarding refs. | |
*/ | |
export function withNextLink< | |
ComponentProps = { | |
href?: string; | |
[prop: string]: unknown; | |
} | |
>( | |
// Then we need to type the incoming component. | |
// This creates a union type of whatever the component | |
// already accepts AND our extraInfo prop | |
WrappedComponent: React.ComponentType<ComponentProps> | |
) { | |
const ComponentWithNextLink: React.FunctionComponent< | |
LinkProps & ComponentProps | |
> = ({ href, as, replace, scroll, shallow, prefetch, locale, ...props }) => { | |
// If we have a href prop found, wrap it in a NextLink. | |
if (href) { | |
return ( | |
<NextLink | |
href={href} | |
as={as} | |
replace={replace} | |
scroll={scroll} | |
shallow={shallow} | |
prefetch={prefetch} | |
locale={locale} | |
passHref | |
> | |
<WrappedComponent {...(props as ComponentProps)} /> | |
</NextLink> | |
); | |
} | |
return <WrappedComponent {...(props as ComponentProps)} />; | |
}; | |
ComponentWithNextLink.displayName = `withNextLink(${ | |
WrappedComponent.displayName || "AnonymousComponent" | |
})`; | |
return ComponentWithNextLink; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment