Skip to content

Instantly share code, notes, and snippets.

@gustavoguichard
Last active June 10, 2020 21:06
Show Gist options
  • Save gustavoguichard/97375631307433f5cd4fb57eff88cf46 to your computer and use it in GitHub Desktop.
Save gustavoguichard/97375631307433f5cd4fb57eff88cf46 to your computer and use it in GitHub Desktop.
const useOpenExternalLinksInNewTab = (el = typeof document === 'undefined' ? null : document) => {
useEffect(() => {
if (el && typeof window !== 'undefined') {
const links = el.querySelectorAll(
`a[href*="//"]:not([href*="${window.location.host}"])`,
)
links.forEach((link) => {
link.setAttribute('target', '_blank')
link.setAttribute('rel', 'noopener')
})
}
}, [el])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment