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>
?
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 thehref
.In this case, you can use react-router's
withRouter
to get thehistory
object, and to use thepush
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):