Jay P.
Jay P.

Reputation: 2590

How to let string coming with HTML tags to be rendered in React js?

I'm working on my website with Reactjs and Django. I have WISYWIG eidtor in Django admin, so when I publish posts with text decorations, it's stored with HTML tags.

In React, I fetch the API from Django REST framework to get the post. When I render the string data in React, it just shows up with HTML tags.

For example,

Django Admin I store Hello, world! and it's stored as <b>Hello, world!</b>. Then, I make API with it.

In React,

I fetch the API and render it in React component, but it just shows up like <b>Hello, world!</b>, insteand of Hello, world!.

Should I use any module to render it like that?

UPDATE

Here are the codes where I have the problem.

{storeList.map(store => {
  return (
    <Card className={classes.card} key={store.id}>
      <CardBody>
        <div className={classes.cardBody}>
          <h6 className={classes.cardSubtitle}>
            {store.shortDesc} <-- This part has the problem
          </h6>
        </div>
      </CardBody>
    </Card>
  );
})}

Upvotes: 4

Views: 8768

Answers (1)

JoeCo
JoeCo

Reputation: 705

You might need to provide a bit more context around your actual issue but I'll venture trying to help. If you have a string that includes HTML tags, then when rendering, use the dangerouslySetInnerHtml property

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

this will then property render the HTML. For more info see https://reactjs.org/docs/dom-elements.html

EDIT:

{storeList.map(store => {   return (
    <Card className={classes.card} key={store.id}>
      <CardBody>
        <div className={classes.cardBody}>
          <h6 className={classes.cardSubtitle}>
             <div dangerouslySetInnerHTML={{ __html: store.shortDesc }} />;
          </h6>
        </div>
      </CardBody>
    </Card>   ); })}

Upvotes: 10

Related Questions