htmlreactjstypescriptparsing

Parse string as HTML in typescript


I am using typescript.

i have and object called Reason as below. i have defined all the variables in the object as string. (value, display, dataType and label as string)

    Reason = {
            value: '<ul><li>list item 1</li><li>list item 2</li></ul>',
            display: '<ul><li>list item 1</li><li>list item 2</li></ul>', 
            dataType: 'string', 
            label: 'Reason'}

I want to display this in a div or span tag.

    <div> {Reason.value} </div>

it is not getting displayed as

rather it prints it as string as <ul><li>list item 1</li><li>list item 2</li></ul>

please let me know how to parse this text to display it in list elements instead of text.


Solution

  • When you do {Reason.value} it assumes Reason.value is text so it escapes all the HTML characters you are using.

    To accomplish what you want you'll need to manually set the HTML.

    In react you do this with dangerouslySetInnerHtml - this can leave you vulnerable to XSS attacks.

    <div dangerouslySetInnerHTML={{ __html: Reason.value }}></div>