Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to use React links when rendering content with dangerouslySetInnerHtml?

So I'm developing a blog page for a react application. The page is loading data from a CMS and the content of the blog post is raw html which I render on the page with:

<div dangerouslySetInnerHTML={{__html: this.state.content}} />

However any links I put in the post like <a href='/'>Home Page</a> don't use react router and instead trigger reloading the page.

Is there a way to handle this in react without having to parse the HTML and replace <a> tags with <Link>?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use a click handler on the HTML container to catch clicks. If the click originates from an <a> tag (or a childrn of), you can prevent default, and use the href.

In this case, you can use react-router's withRouter to get the history object, and to use the push method to notify the router. You can also edit the url, or manipulate it in other ways.

Example (uncomment and remove the console when you use the code):

// import { withRouter } from 'react-router-dom'

class HTMLContent extends React.Component {
  contentClickHandler = (e) => {
    const targetLink = e.target.closest('a');
    if(!targetLink) return;
    e.preventDefault();
    
    console.log(targetLink.href); // this.props.history.push(e.target.href)
  };
  
  render() {
    return (
      <div 
        onClick={this.contentClickHandler}
        dangerouslySetInnerHTML={{__html: this.props.content}} 
      />
    );
  }
}

// export default withRouter(HTMLContent);

const content = `<div>
  <a href="http://www.first-link.com">Link 1</a>
  <a href="http://www.second-link.com"><span>Link 2</span></a>
</div>`;

ReactDOM.render(
  <HTMLContent content={content} />,
  demo
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...