You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Chakra UI的React项目中,dangerouslySetInnerHTML无法渲染<Code>组件的技术问询

Why Your Chakra UI 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.

  1. Install the package first:

    npm install html-react-parser
    # or
    yarn add html-react-parser
    
  2. Update your code with a custom replacement handler:

    import { Code } from "@chakra-ui/react";
    import parse from "html-react-parser";
    
    const test = `text text &lt;Code&gt;text&lt;/Code&gt;`;
    
    // 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:50:19