使用html-react-parser时,如何将SVG前置到HTML内容并正常渲染?
Got it, let's break down why you're seeing that [object Object] mess and fix it properly. The core issue here is straightforward: when you use html-react-parser on your SVG file, it returns a React element object—not a plain string. When you try to concatenate this object with your HTML string (imgTag + htmlData), JavaScript converts the object to its default string representation: [object Object]. That's exactly what's showing up in your result.
Here are two solid, React-friendly solutions to get your SVG and HTML content displaying together correctly:
Solution 1: Parse Both SVG and HTML into React Elements (Recommended)
Since you're working in React, the cleanest approach is to convert your HTML string into a React element too, then render both the SVG element and parsed HTML together in a React fragment or container. This keeps everything aligned with React's rendering system.
import * as Parser from 'html-react-parser'; // Use import instead of require for React projects (more standard practice) import loadingLogo from './img/loading.svg'; const htmlData = 'hello <b>World</b>'; // Parse the SVG into a React element and set its attributes const svgElement = Parser(loadingLogo); svgElement.props.height = "20"; svgElement.props.width = "100"; // Parse your HTML string into a React element const parsedHtml = Parser(htmlData); // Combine them into a single renderable React output const output = ( <> {svgElement} {parsedHtml} </> ); // Now you can render `output` in your component like any other React element
Solution 2: Combine as Strings First, Then Parse
If you prefer to manipulate content as strings before rendering, you can import the SVG as raw text, combine it with your HTML string, then parse the whole thing into a React element. Note that this requires your bundler (Webpack, Vite, etc.) to support importing SVG files as raw text (usually done with a ?raw suffix).
import * as Parser from 'html-react-parser'; // Add ?raw to import the SVG as a raw string (adjust based on your bundler's setup) import loadingLogo from './img/loading.svg?raw'; const htmlData = 'hello <b>World</b>'; // Create an img tag string with your SVG source and attributes, then concatenate with HTML const combinedHtml = `<img src="${loadingLogo}" height="20" width="100" />${htmlData}`; // Parse the combined string into a React element const output = Parser(combinedHtml);
内容的提问来源于stack exchange,提问作者Newton Sheikh

