Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

reactjs - Handling static links from Wordpress API page content in React Router

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 yourwebsite.com/about/ 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?

question from:https://stackoverflow.com/questions/65845498/handling-static-links-from-wordpress-api-page-content-in-react-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...