4

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>
  );
})}
2

1 Answer 1

10

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>   ); })}
3
  • Sorry for making broad question. I'm kind of lost to properly use dangerouslySetInnerHTML in my codes. Should I use it right away before passing through props? Also, updated the post with my codes
    – Jay P.
    Oct 11, 2018 at 18:47
  • @Jay does the edit help? I think I'm understanding what you're trying to do.
    – JoeCo
    Oct 11, 2018 at 19:58
  • 1
    It helped a lot! It says it needs __html thing so edited your post to make sure. Thank you for the help @JoeCo!
    – Jay P.
    Oct 11, 2018 at 20:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.