I used react-html-parser
as suggested by cbr in the comments. The documentation for implementing the transform function was minimal, so below is how I completed it:
export default function ContentBlock({
children, className, tagName
}) {
const Tag = tagName;
const domain = 'www.yourdomain.co.uk';
function transform(node) {
// convert <a> to React-Router <Link>
if (node.type === 'tag' && node.name === 'a') {
// Only apply the transform to internal links
if(node.attribs.href.indexOf(domain) > 0) {
const href = node.attribs.href.split(domain)[1].split('/')[1];
const classes = node.attribs.class ? node.attribs.class : '';
const label = node.children[0].data;
return <Link to={`/${href}`} className={classes}>{label}</Link>
}
}
}
return (
<Tag className={className} >
{ ReactHtmlParser(children, {transform}) }
</Tag>
)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…