使用Chakra UI的React项目中,dangerouslySetInnerHTML无法渲染<Code>组件的技术问询
Component Isn't Rendering with dangerouslySetInnerHTML Got it, let's break down the problem first: dangerouslySetInnerHTML only handles native HTML elements—it doesn't recognize React components like Chakra UI's <Code>. When your string gets decoded to <Code>, React treats it as an unknown HTML tag, not the styled Chakra component you want. That's why the formatting never kicks in.
Here are two solid solutions to fix this:
Solution 1: Use html-react-parser to Convert HTML Strings to React Elements
This library lets you parse HTML strings into actual React components, and you can explicitly map the <Code> tag to Chakra's version.
Install the package first:
npm install html-react-parser
# or
yarn add html-react-parser
Update your code with a custom replacement handler:
import { Code } from "@chakra-ui/react";
import parse from "html-react-parser";
const test = `text text <Code>text</Code>`;
// Map parsed <code> tags (lowercase after parsing) to Chakra's Code component
const replaceTag = (domNode) => {
if (domNode.name === "code") {
const codeContent = domNode.children.map(child => child.data).join("");
return <Code>{codeContent}</Code>;
}
};
export default function YourComponent() {
return <div>{parse(test, { replace: replaceTag })}</div>;
}
Note: HTML parsers convert tags to lowercase, so we check for "code" instead of "Code".
Solution 2: Custom Markers + Manual Parsing (Safer for Untrusted Content)
If you're working with user-generated content (or want to avoid HTML parsing entirely), swap the <Code> tags for a custom syntax (like [code]...[/code]) and split the string to render React elements directly:
import { Code } from "@chakra-ui/react";
const test = `text text [code]text[/code]`;
const renderFormattedContent = () => {
return test.split(/\[code\]|\[\/code\]/).map((segment, index) => {
// Odd indexes are the content inside [code] tags
return index % 2 === 1 ? <Code key={index}>{segment}</Code> : segment;
});
};
export default function YourComponent() {
return <div>{renderFormattedContent()}</div>;
}
This approach skips dangerouslySetInnerHTML entirely, eliminating XSS risks that come with rendering raw HTML from untrusted sources.
Quick Security Reminder
If you go with HTML parsing or dangerouslySetInnerHTML, always sanitize untrusted input first (e.g., using dompurify alongside html-react-parser) to block malicious code injection.
内容的提问来源于stack exchange,提问作者wifykyty

