Reputation: 101
I'm using a headless approach for a React (Next.js) + Wordpress API app.
The problem I'm running into is when the content editor adds an anchor tag into WP's WYSIWYG editor. I'm parsing that content using React's dangerouslySetInnerHTML
and therefore a plain <a href="whatever">
is generated.
How do I go about transforming that into a next.js
<Link>
tag?
Not sure if this helps, but this is a piece of my code:
<React.Fragment>
<h1>Page: {title.rendered}</h1>
<div
className="richtext"
dangerouslySetInnerHTML={{ __html: content.rendered }}
></div>
{wpData.acf.modules.map((mod, index) => (
<React.Fragment key={`module=${index}`}>
{renderComponents(mod)}
</React.Fragment>
))}
</React.Fragment>
Since I'm using a decoupled solution, the anchor tag points to the server url, which leads to a broken page.
Upvotes: 3
Views: 2215
Reputation: 101
Ok, so the solution I found was posted here: https://stackoverflow.com/a/51570332/11983936
Basically factored the content display into its own helper function and used that in the components I need:
import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { useRouter } from 'next/router';
import fixLink from './fixLink';
const useRenderRichtext = props => {
const router = useRouter();
const handleAnchorClick = e => {
const targetLink = e.target.closest('a');
if (!targetLink) return;
e.preventDefault();
const redirectThis = fixLink(targetLink.href);
router.push(`/${redirectThis}`);
};
return (
<Fragment>
<div
onClick={handleAnchorClick}
onKeyPress={handleAnchorClick}
className="richtext"
dangerouslySetInnerHTML={{ __html: props }}
></div>
</Fragment>
);
};
export default useRenderRichtext;
Upvotes: 6