Links
Using Next.js Link component for inline links in body fields.
To replace inline <a />
tags with the Next.js Link
component, we can use an html parser like we did for images.
Dependencies
Install html-react-parser.
yarn add html-react-parser
Component
Update the component from images to handle inline links.
components/body.tsx
import { HTMLReactParserOptions, domToReact } from "html-react-parser" import { Element } from "domhandler/lib/node"import parse from "html-react-parser"import Image from "next/image"import Link from "next/link"
const options: HTMLReactParserOptions = { replace: (domNode) => { if (domNode instanceof Element && domNode.name === "img") { const { src, alt, width, height } = domNode.attribs
return ( <Image src={`${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/${src}`} width={`${width}px`} height={`${height}px`} alt={alt} layout="intrinsic" objectFit="cover" /> ) }
if (domNode.name === "a") { const { href, class: className } = domNode.attribs
return ( <Link href={href} passHref> <a className={className}>{domToReact(domNode.children)}</a> </Link> ) } },}
export function Body({ value }: { value: string }) { return <>{parse(value, options)}</>}
Usage
pages/index.tsx
import { Body } from "components/body"
export default function Page({ node }) { return ( <div variant="container"> <h1>{node.title}</h1> <Body value={node.body.processed} /> </div> )}
Learn more about next/link.