0

I have a string that have a <a> text </a> tag in it, but it was just read by the browser as a plain text when displayed inside a ReactJS's element,

Here is my sample code

const datas = [
    {
        title: 'the title1',
        description: `the link was in <a href="#">here</a>, please click`
    },
    {
        title: 'the title2',
        description: `the link was in the last <a href="#">word</a>`
    }
]


const renderDatas = () => {
    return datas.map(data => {
        return (
            <div>
                {data.description}
            </div>
        )
    })
}

I already tried the accepted answer here and the only difference is, I'm using a string literal (`), but it just only read by the browser as plain text either.

My expected result was to make that <a href="#">here</a> a clickable link when the browser reads it.

Dylan
  • 1,121
  • 1
  • 13
  • 28
  • It's unclear *how* you've tried that accepted answer, given that you haven't used what that *question* did. As far as we can see you're not currently trying to set the HTML. – jonrsharpe Nov 29 '20 at 11:13

1 Answers1

1

I think, you can use dangerouslySetInnerHTML prop of div. For example:

const renderDatas = () => {
    return datas.map(data => {
        return (
            <div dangerouslySetInnerHTML={{ __html: data.description }} />
        )
    })
}

But, note, that, as the documentation says: In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

Alex Shul
  • 500
  • 7
  • 22