Created
April 18, 2021 19:35
-
-
Save andrewfairlie/85bc685c4534b57d14018dd78a55161f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 * as React from 'react' | |
import { useRouter } from 'next/router' | |
type HtmlOutputType = { | |
content: string | |
} | |
const HtmlOutput: React.FunctionComponent<HtmlOutputType> = ({ content }) => { | |
const router = useRouter() | |
// Prefetch any URLs in the content | |
React.useEffect(() => { | |
const detectLinkRegex = /href="(.*?)"/g | |
let link | |
while ((link = detectLinkRegex.exec(content))) { | |
if (link[1].startsWith('/')) { | |
router.prefetch(link[1]) | |
} | |
} | |
}, []) | |
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => { | |
const targetLink = (e.target as HTMLDivElement).closest('a') | |
// If there's no link, exit out of this early on | |
if (!targetLink) return | |
// If the link isn't a relative link, exit out | |
const href = targetLink.getAttribute('href') | |
if (!href || !href.startsWith('/')) return | |
// Tell next to route to it | |
router.push(targetLink.href) | |
e.preventDefault() | |
} | |
return <div onClick={handleClick} dangerouslySetInnerHTML={{ __html: content }} /> | |
} | |
export default HtmlOutput |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment