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?

2
  • Possible duplicate of Reactjs convert to html Commented Feb 23, 2018 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. Commented Feb 23, 2018 at 20:20

1 Answer 1

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

4 Comments

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!
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 <p dangerouslySetInnerHTML={{__html: example.phraseWithHtml}} />.
I updated the code for you @ooloth. Someone else edited my answer and added that code, so I added another edit for you.
Lovely. Just wanted to make sure a future newbie could copy/paste with no issues.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.