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>
?
However, if the application or site accepts multiple users' data input, you should be concerned. However, apart from that, there is one alternative to using dangerouslySetInnerHTML, simply setting innerHTML of a React HTML element using vanilla JS instead.
In conclusion, dangerouslySetInnerHTML is nothing but a replacement of innerHTML in React and should be used with care.
The dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML , it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With