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
  • Please provide a minimal reproducible example Commented Oct 11, 2018 at 18:22
  • @Code-Apprentice Updated it! Commented Oct 11, 2018 at 18:45

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>   ); })}
Sign up to request clarification or add additional context in comments.

3 Comments

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 does the edit help? I think I'm understanding what you're trying to do.
It helped a lot! It says it needs __html thing so edited your post to make sure. Thank you for the help @JoeCo!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.