0

I use react-router-dom library NavLink component. Sometimes I need to use an external link in NavLink component but I get this as result:

localhost:8080/https://google.com

There is some default setting for it to distinguish between these cases, or better write my own?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

0

not to lose SPA

import React, {FC, PropsWithChildren} from "react";
import {NavLink as BaseNavLink, NavLinkProps} from 'react-router-dom'

const NavLink: FC<PropsWithChildren<{to: string} & NavLinkProps>> = ({children,to, ...props}) => {
  const regExternalLink = /(https?:\/\/)?[\w\-~]+(\.[\w\-~]+)+(\/[\w\-~@:%]*)*(#[\w\-]*)?(\?[^\s]*)?/
  const isExternalLink = regExternalLink.test(to)

  return isExternalLink
    ? <a href={to}>{children}</a>
    : <BaseNavLink to={to}>{children}</BaseNavLink>
}