1

I'm storing text content in a JSON file and outputting it in JSX. (In my case, I'm using Gatsby and querying the JSON using GraphQL.)

For example, the following JSON...

// example.json
[
  { "phrase": "Hello, world!" },
  { "phraseWithHTML": "<em>Hello</em>, <a href=\"https://example.com\">world!</a>" }
]

...is output in the following JSX:

// ...
<p>{example.phrase}</p>
<p>{example.phraseWithHtml}</p>
// ...

In both cases, the strings are output as plain text (i.e. phraseWithHtml is displayed as a string rather than the intended: Hello world.

Is there a way to output example.phraseWithHTML as HTML instead? Do I need to store it differently in the JSON file? Is there a way to transform it in the JSX?

ooloth
  • 345
  • 4
  • 14
  • Possible duplicate of [Reactjs convert to html](https://stackoverflow.com/questions/19266197/reactjs-convert-to-html) – Michael Jasper Feb 23 '18 at 19:55
  • Agreed. I did a ton of Googling and didn't come across it, though, so hopefully the way I've asked the question here will help someone who uses similar search terms to mine. – ooloth Feb 23 '18 at 20:20

1 Answers1

4

You can use the Dangerously Set innerHTML functionality from React to do this.

// ...
<p>{example.phrase}</p>
<p dangerouslySetInnerHTML={ return {__html: example.phraseWithHtml}; }></p>
// ...
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
  • If this is the correct answer for you, then can you please select it as the Accepted Answer so people can see it in the future? Thanks! – th3n3wguy Feb 23 '18 at 20:07
  • Yup! I will. Just wondering about the code you added to answer - should there be an `__html: ` inside the brackets and before the `example.phraseWithHtml`? I think there might also need to be a second level of `{}` there as well... The final version would be `

    `.
    – ooloth Feb 23 '18 at 20:09
  • I updated the code for you @ooloth. Someone else edited my answer and added that code, so I added another edit for you. – th3n3wguy Feb 23 '18 at 20:12
  • 1
    Lovely. Just wanted to make sure a future newbie could copy/paste with no issues. – ooloth Feb 23 '18 at 20:13