简体   繁体   中英

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> ?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM