Hesam
Hesam

Reputation: 53600

How to display dynamic HTML correctly?

I have an object called article that comes from the backend. It contains id, title and description. The description contains HTML data and I want to be parsed as HTML code by browser however, browser treats it as text. So, I am wondering why. And how to ask browser to parse it as HTML?

interface BodyComponentProps {
    name: string;
    article: article;
}

class BodyComponent extends React.Component<BodyComponentProps> {

    public render() {
        const art = this.props.article;

        return (
            /* <!-- Main container --> */
            <nav className="level body-container">
                {/* <!-- Left side --> */}
                <div className="level-left">
                    <div className="level-item">
                        <nav className="panel content-block">
                            <p className="panel-heading">{art.title}</p>
                            <div className="panel-block">{art.description}</div>
                        </nav>
                    </div>
                </div>

                {/* <!-- Right side --> */}
                <div className="level-right">
                    <div className="level-item sidebar-item">
                        <SidebarPanel title={this.props.name}/>
                    </div>
                </div>
            </nav>
        );
    }
}

const mapStateToProps = (state: NahjReduxState) => ({
    article: state.content.article,
});

export default connect(mapStateToProps)(BodyComponent);

enter image description here

Upvotes: 0

Views: 52

Answers (1)

tskjetne
tskjetne

Reputation: 2354

React treats it as text, not HTML, for security reasons. Allowing inserting HTML from the backend means you're opening your site up for cross-site scripting (XSS - https://en.wikipedia.org/wiki/Cross-site_scripting). Cross-site scripting (XSS) means that malicious scripts can be injected into your website by other people.

However, if you truly want to do this, you can use the dangerouslySetInnerHtml prop. dangerouslySetInnerHtml requires you to pass an object with the key __html (notice the double underscore), and the value is the HTML you want to render.

Example:

<div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

React dangerouslySetInnerHtml docs

Upvotes: 1

Related Questions