Last active
July 3, 2021 09:29
-
-
Save mobeigi/271d64ea1c60a8a398ec9257806d208d to your computer and use it in GitHub Desktop.
React Router Link for internal/external 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
/** | |
* TargetAwareLink | |
* Will either return Link or Anchor link depending on if link is an internal/external link. | |
*/ | |
import React, { AnchorHTMLAttributes, PropsWithChildren } from 'react'; | |
import { Link as RouterLink } from 'react-router-dom'; | |
import type { LinkProps } from 'react-router-dom'; | |
type TargetAwareLinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & | |
LinkProps & { | |
forceReload?: boolean; | |
}; | |
export const TargetAwareLink = ({ | |
to, | |
forceReload = false, | |
children, | |
...props | |
}: PropsWithChildren<TargetAwareLinkProps>) => | |
forceReload || /^https?:\/\//.test(to.toString()) ? ( | |
// eslint-disable-next-line react/jsx-props-no-spreading | |
<a href={to.toString()} {...props}> | |
{children} | |
</a> | |
) : ( | |
// eslint-disable-next-line react/jsx-props-no-spreading | |
<RouterLink to={to} {...props}> | |
{children} | |
</RouterLink> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment