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

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...