escaping html tags in meteor react

- 1 answer

Ad

I have the following react component

homeComponent = React.createClass({
    mixins: [ReactMeteorData],
    getMeteorData() {
        return {
            homeData: homeContent.findOne()
        }
    },
    render(){
        let homeData = this.data.homeData;
        return (
            <div className="units-container home-container">
                <h1>ply</h1>
                <p>{homeData.homeCopy}</p>
                <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{homeData.downloadLink}" className="btn home-button">Download</a>
            </div>
        )
    }
})

The key {homeData.homeCopy} returns a string that has html tags in. So in this case let's say it returns <strong>bold text</strong> not bold text.

I'm using react-template-helper to use both blaze and react, so I would expect that I could use triple brackets to escape the html, but that's not working. I need to escape the html from react I suppose.

How can I get react to honor these html tags from the string?

Ad

Answer

Ad

@mason505 pointed this in the right direction, but I think this needs some extra information.

First you must make a function to parse the html:

function escapeHTML(data) {
    return {__html: data}
}

Then you must call that with dangerouslySetInnerHTML but only on a self enclosed html element and you must pass the data into dangerouslySetInnerHTML using the escapeHTML function. Complete example is:

function escapeHTML(data) {
    return {__html: data}
}

homeComponent = React.createClass({
    mixins: [ReactMeteorData],
    getMeteorData() {
        return {
            homeData: homeContent.findOne()
        }
    },
    render(){
        let homeData = this.data.homeData;

        return (
            <div className="units-container home-container">
                <h1>ply</h1>
                <p dangerouslySetInnerHTML={escapeHTML(homeData.homeCopy)} />
                <a href={homeData.downloadLink} className="btn home-button">Download</a>
            </div>
        )
    }
})
Ad
source: stackoverflow.com
Ad