Sisir
Sisir

Reputation: 43

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.

Upvotes: 1

Views: 7190

Answers (2)

Ik32
Ik32

Reputation: 61

I just found the solution in my project - React- typescript where I'm fetching html block from different service. Here is the simplified version

type Props = {
    htmlString: string;
};

export function HtmlStringComponent({ htmlString }: Props) {

     return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
}

Upvotes: 0

RobPethi
RobPethi

Reputation: 571

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>

Upvotes: 2

Related Questions