Files
web/hooks/useCheckIfExternalLink.ts
Linus Flood 09777ee909 PR fixes
2024-10-21 09:53:40 +02:00

24 lines
655 B
TypeScript

import { useEffect, useState } from "react"
export const useCheckIfExternalLink = (url: string) => {
const [isExternal, setIsExternal] = useState(false)
useEffect(() => {
if (typeof window !== "undefined" && url?.length) {
try {
const hostName = window.location.hostname
const newURL = new URL(url)
const hostsMatch = hostName === newURL.hostname
const langRouteRegex = /^\/[a-zA-Z]{2}\//
setIsExternal(!hostsMatch || !langRouteRegex.test(newURL.pathname))
} catch {
// Don't care. Expecting internal url (#, /my-pages/overview, etc)
}
}
}, [url])
return isExternal
}