Handling static links from WordPress API page content in React Router

Rate this post

I’m building a react app with React Router using wordpress as a headless cms, and I’ve come across a problem where I can’t handle the links within the page content. I edited the link from to /about within WordPress, and the routing works on the frontend, but it refreshes the page at the same time. Is there a way of telling router to see these static content links as routes?



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 = '';

  function transform(node) {
    // convert <a> to React-Router <Link>
    if (node.type === 'tag' && === '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}) }

Leave a Reply

Your email address will not be published.

Back to top button