Displaying server-sent HTML content in React components

Hey folks, I’m stuck on a React issue. I’m getting HTML as a string from my backend, and I want to show it in my React component. I’ve tried passing it as props and rendering it directly in JSX, but no luck. Here’s what I’ve attempted:

import React, { Component } from 'react'

class ContentDisplay extends Component {
  state = {
    htmlContent: ''
  }
  
  async componentDidMount() {
    const { fetchData } = this.props
    const result = await fetchData()
    this.setState({ htmlContent: result })
  }

  render() {
    const { htmlContent } = this.state
    return (
      <div>
        {/* Tried this */}
        <div>{htmlContent}</div>
        {/* And this */}
        <htmlContent />
      </div>
    )
  }
}

I’m not sure if I should use renderProps or dangerouslySetInnerHTML. Any ideas on how to render this HTML safely without messing with the DOM directly? Thanks!

yo, have u tried dangerouslySetInnerHTML? it’s built into react and works great for this. just be careful with the html source to avoid security issues. here’s a quick example:

it’s simple but gets the job done. lmk if u need more help!

ooh, interesting problem! have u considered using a library like react-html-parser? it’s pretty nifty for handling html strings in react components. just curious, what kind of content are u trying to display? maybe there’s a more specific solution depending on the use case? let me know if u want to brainstorm some ideas!

I’ve encountered this issue before, and the safest way to handle it is by using dangerouslySetInnerHTML. While the name sounds intimidating, it’s actually React’s built-in solution for rendering HTML strings. Here’s how you can modify your component:

render() {
  const { htmlContent } = this.state;
  return (
    <div dangerouslySetInnerHTML={{ __html: htmlContent }} />
  );
}

Just be cautious about the source of your HTML content. Ensure it’s from a trusted source to prevent XSS attacks. If you need more control over the rendered elements, consider using a library like DOMPurify to sanitize the HTML before rendering. This approach has worked well for me in production environments where we needed to display server-generated HTML content within React components.