Created
November 29, 2021 19:34
-
-
Save nandorojo/e0b09c17571f6e7852f9ba265a566c36 to your computer and use it in GitHub Desktop.
React Native + Next.js Link Components
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 type { ComponentProps, ComponentType } from 'react' | |
import { | |
Platform, | |
Pressable, | |
Text, | |
TextProps, | |
ViewProps, | |
View, | |
} from 'react-native' | |
import { useLinkProps } from '@react-navigation/native' | |
import NextLink from 'next/link' | |
const parseNextPath = (from: Parameters<NextRouter['push']>[0]) => { | |
let path = (typeof from == 'string' ? from : from.pathname) || '' | |
// replace each instance of [key] with the corresponding value from query[key] | |
// this ensures we're navigating to the correct URL | |
// it currently ignores [...param] | |
// but I can't see why you would use this with RN + Next.js | |
if (typeof from == 'object' && from.query && typeof from.query == 'object') { | |
const query = { ...from.query } | |
for (const key in query) { | |
if (path.includes(`[${key}]`)) { | |
path = path.replace(`[${key}]`, `${query[key] ?? ''}`) | |
delete query[key] | |
} | |
} | |
if (Object.keys(query).length) { | |
path += '?' | |
for (const key in query) { | |
if (query[key] != null) { | |
path += `${key}=${query[key]}&` | |
} | |
} | |
if (path.endsWith('&')) { | |
path = path.slice(0, -1) | |
} | |
} | |
} | |
return path | |
} | |
type Props = { | |
children: React.ReactNode | |
} & Omit<ComponentProps<typeof NextLink>, 'passHref'> | |
function LinkCore({ | |
children, | |
href, | |
as, | |
componentProps, | |
Component, | |
...props | |
}: Props & { | |
Component: ComponentType<any> | |
componentProps?: any | |
}) { | |
if (Platform.OS === 'web') { | |
return ( | |
<NextLink {...props} href={href} as={as} passHref> | |
<Component {...componentProps}>{children}</Component> | |
</NextLink> | |
) | |
} | |
// eslint-disable-next-line react-hooks/rules-of-hooks | |
const linkProps = useLinkProps({ | |
to: parseNextPath(href), | |
}) | |
return ( | |
<Component {...componentProps} {...linkProps}> | |
{children} | |
</Component> | |
) | |
} | |
type LinkProps = Props & { viewProps?: ViewProps } | |
function Link({ viewProps, ...props }: LinkProps) { | |
return ( | |
<LinkCore | |
{...props} | |
Component={Platform.select({ | |
web: View, | |
default: Pressable as any, | |
})} | |
componentProps={viewProps} | |
/> | |
) | |
} | |
type TextLinkProps = Props & { textProps?: TextProps } | |
function TextLink({ textProps, ...props }: TextLinkProps) { | |
return <LinkCore {...props} Component={Text} componentProps={textProps} /> | |
} | |
export { Link, TextLink, LinkCore } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment