如何在JSX中以HTML形式输出JSON存储的字符串?(Gatsby+GraphQL)
Absolutely! You can render the HTML content from your phraseWithHTML field directly in JSX without changing how you store it in JSON—though you’ll need to adjust your component code to handle unescaped HTML. Here’s how to do it properly in Gatsby:
1. Use React's dangerouslySetInnerHTML
React automatically escapes HTML strings to prevent XSS attacks, which is why your phraseWithHTML is showing up as plain text. To bypass this and render the actual HTML, use the dangerouslySetInnerHTML prop.
First, confirm your GraphQL query is pulling in the field correctly (adjust the query to match your JSON source's structure):
query ExampleQuery { exampleJson { phraseWithHTML } }
Then implement it in your component:
import React from "react" export default function ExampleComponent({ data }) { const { phraseWithHTML } = data.exampleJson return ( {/* Render the raw HTML content */} <div dangerouslySetInnerHTML={{ __html: phraseWithHTML }} /> ) }
2. Add XSS Protection (Critical!)
The "dangerously" in the prop name is a warning: if your HTML content comes from untrusted sources (like user input), it can expose your site to cross-site scripting attacks. To mitigate this, sanitize the HTML with a library like dompurify.
First install the library:
npm install dompurify
Then update your component to sanitize the HTML before rendering:
import React from "react" import DOMPurify from "dompurify" export default function ExampleComponent({ data }) { const { phraseWithHTML } = data.exampleJson // Remove any malicious code from the HTML string const sanitizedHtml = DOMPurify.sanitize(phraseWithHTML) return ( <div dangerouslySetInnerHTML={{ __html: sanitizedHtml }} /> ) }
3. Do You Need to Adjust Your JSON?
Nope! You can keep storing phraseWithHTML as a regular HTML string in your JSON file (e.g., "phraseWithHTML": "<h1>Hello world</h1>"). No changes to your data structure are required—all the work happens in your React component.
Quick Alternative Note
If you ever want to switch to Markdown instead of raw HTML in your JSON, Gatsby has plugins like gatsby-transformer-remark that can parse Markdown into HTML. But for your current use case, sticking with raw HTML strings and using dangerouslySetInnerHTML (with sanitization) is the simplest solution.
内容的提问来源于stack exchange,提问作者ooloth

