{"id":11875,"library":"react-svg","title":"React SVG Component","description":"react-svg is a React component designed to fetch SVG files from a given URL and inject their raw markup directly into the DOM, rather than rendering them as `<img>` tags. This approach, powered by the underlying `@tanem/svg-injector` library, enables full manipulation of the SVG's internal elements via CSS and JavaScript, unlocking possibilities like dynamic styling, animation, and interactivity that are not possible with traditional `<img>` elements. It also features client-side caching of fetched SVGs to reduce redundant network requests for repeated assets. The package is actively maintained, with its current stable version being 17.2.4, and exhibits a healthy release cadence, often seeing updates within a three-month window. It ships with TypeScript type definitions, enhancing development in TypeScript environments.","status":"active","version":"17.2.4","language":"javascript","source_language":"en","source_url":"https://github.com/tanem/react-svg","tags":["javascript","dom","html","images","img","react","scalable vector graphics","svg","typescript"],"install":[{"cmd":"npm install react-svg","lang":"bash","label":"npm"},{"cmd":"yarn add react-svg","lang":"bash","label":"yarn"},{"cmd":"pnpm add react-svg","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core SVG injection logic.","package":"@tanem/svg-injector","optional":false},{"reason":"Peer dependency for React applications.","package":"react","optional":false},{"reason":"Peer dependency for React applications.","package":"react-dom","optional":false}],"imports":[{"note":"Primary named export for the component. CommonJS users should use destructuring require.","wrong":"const ReactSVG = require('react-svg')","symbol":"ReactSVG","correct":"import { ReactSVG } from 'react-svg'"},{"note":"Type import for component props when using TypeScript.","symbol":"ReactSVGProps","correct":"import type { ReactSVGProps } from 'react-svg'"},{"note":"While `react-svg` uses `SVGInjector` internally, advanced use cases might require direct interaction with the underlying injection library for global configuration or manual injection.","symbol":"SVGInjector","correct":"import { SVGInjector } from '@tanem/svg-injector'"}],"quickstart":{"code":"import { createRoot } from 'react-dom/client';\nimport { ReactSVG } from 'react-svg';\n\nconst rootElement = document.getElementById('root');\n\nif (rootElement) {\n  const root = createRoot(rootElement);\n  root.render(\n    <div>\n      <h1>My Application</h1>\n      <p>Loading an external SVG using ReactSVG:</p>\n      <ReactSVG\n        src=\"/path/to/your/image.svg\"\n        beforeInjection={(svg) => {\n          console.log('SVG about to be injected:', svg.id);\n          svg.setAttribute('style', 'width: 100px; height: 100px;');\n        }}\n        afterInjection={(svg) => console.log('SVG injected:', svg.id)}\n        onError={(error) => console.error('Error loading SVG:', error.message)}\n        loading={() => <span style={{ color: 'blue' }}>Loading SVG...</span>}\n        fallback={() => <span style={{ color: 'red' }}>Could not load SVG</span>}\n      />\n      <p>Ensure 'image.svg' is accessible at the specified path.</p>\n    </div>\n  );\n} else {\n  console.error(\"Root element 'root' not found.\");\n}","lang":"typescript","description":"Demonstrates basic usage of `ReactSVG` to load an external SVG, including lifecycle callbacks, error handling, and a loading fallback. It highlights DOM manipulation before injection."},"warnings":[{"fix":"Provide a valid URL string to the `src` prop. If using raw SVG markup, parse it with `DOMParser` and append it, or use `dangerouslySetInnerHTML` after careful sanitization.","message":"Directly injecting SVG markup (e.g., as a string literal) via the `src` prop is not supported. The `src` prop expects a URL to an SVG file. If you have SVG markup as a string, consider using `dangerouslySetInnerHTML` with appropriate sanitization or a direct DOM manipulation approach.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure the server hosting the SVG to include appropriate CORS headers, specifically `Access-Control-Allow-Origin`, to permit requests from your application's origin. For development, a proxy might temporarily circumvent this.","message":"When fetching SVGs from a different origin (domain, protocol, or port), Cross-Origin Resource Sharing (CORS) policies must be correctly configured on the server hosting the SVG. Without proper CORS headers, the browser will block the resource request, preventing `react-svg` from injecting the SVG.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Always keep `evalScripts` set to its default value of 'never' unless you fully trust the source of all SVGs and understand the security implications. Thoroughly sanitize any user-uploaded or untrusted SVG content on the server-side to strip out malicious scripts before they reach the client.","message":"SVGs can contain embedded scripts (`<script>` tags or event handlers) that, when injected into the DOM, can execute JavaScript. The `evalScripts` prop is designed to control this behavior and defaults to 'never'. Changing this to 'once' or 'always' can introduce Cross-Site Scripting (XSS) vulnerabilities if the SVG content is untrusted or user-supplied.","severity":"security","affected_versions":">=1.0.0"},{"fix":"Minimize frequent changes to the `src` prop if visual smoothness is critical. Consider preloading SVGs or using a CSS transition for the wrapper element to smooth out the transition. For very small, static SVGs, directly inlining them as JSX components or using an `<img>` tag might be preferable if re-injection flashes are problematic.","message":"Changing the `src` prop of a `ReactSVG` component will trigger a re-injection of the SVG. This re-injection process involves removing the old SVG and inserting the new one, which can cause a brief visual 'flash' as the content is swapped.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Populate the `title` prop with a concise, human-readable title and the `desc` prop with a more detailed description for complex SVGs. This improves usability for assistive technologies.","message":"To ensure proper accessibility, especially for screen readers, always provide meaningful `title` and `desc` props for your SVGs, particularly if they convey important information. These props inject `<title>` and `<desc>` elements into the SVG, enhancing its semantic understanding.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify the `src` URL is correct and the SVG file exists at that location. Check network requests in browser developer tools for the exact HTTP status code.","cause":"The `src` prop points to an SVG file that cannot be found or accessed by the browser, often due to an incorrect path or server issue.","error":"Failed to load resource: net::ERR_FAILED"},{"fix":"Configure the server hosting the SVG to send appropriate CORS headers that allow requests from your application's origin. For local development, a Webpack proxy or a browser extension might bypass this, but a server-side fix is essential for production.","cause":"The SVG is being requested from a different origin (domain, protocol, or port) than the current page, and the server hosting the SVG does not send the necessary `Access-Control-Allow-Origin` HTTP header.","error":"Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."},{"fix":"The `src` prop requires a URL string. If you have SVG markup as a string, you must store it as a file and provide its URL, or manually parse and inject it into the DOM outside of `ReactSVG`.","cause":"Attempting to pass raw SVG markup as a string directly to the `src` prop or as children to `ReactSVG`, which expects a URL.","error":"Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, props, ref}). If you meant to render a collection of children, use an array instead. / Or: Invariant Violation: React.Children.only expected to receive a single React element child."},{"fix":"Inspect the injected SVG in the browser's developer tools. Check its dimensions, applied CSS, and the integrity of its internal structure. Ensure `viewBox` is set correctly in the SVG. If using a bundler like Webpack with SVGR, ensure it's configured to output a compatible format or handle namespace tags correctly.","cause":"The SVG is loaded but not displayed correctly due to CSS conflicts, incorrect dimensions, or issues within the SVG markup itself (e.g., missing viewBox, inline styles, or namespace issues when bundled with tools like `@svgr/webpack`).","error":"SVG rendering not working / SVG not visible / broken appearance"}],"ecosystem":"npm"}