An SVG loader for React that enables inline SVG rendering with caching and preprocessing capabilities
npx @tessl/cli install tessl/npm-react-inlinesvg@4.2.0react-inlinesvg is a React component library for loading and displaying SVG files inline within React applications. It supports loading SVGs from remote URLs, local files, base64-encoded strings, and raw SVG markup, with intelligent caching mechanisms to optimize performance and comprehensive customization options.
npm install react-inlinesvgimport InlineSVG from "react-inlinesvg";With types and utilities:
import InlineSVG, {
Props,
ErrorCallback,
LoadCallback,
PreProcessorCallback,
FetchError,
StorageItem,
Status,
State,
PlainObject,
Simplify,
cacheStore,
canUseDOM,
isSupportedEnvironment,
randomString,
request,
sleep,
supportsInlineSVG,
omit,
CACHE_NAME,
CACHE_MAX_RETRIES,
STATUS
} from "react-inlinesvg";For CommonJS:
const InlineSVG = require("react-inlinesvg");import React from "react";
import InlineSVG from "react-inlinesvg";
export default function App() {
return (
<main>
<InlineSVG
src="https://cdn.svgporn.com/logos/react.svg"
width={128}
height="auto"
title="React Logo"
onLoad={(src, isCached) => console.log(`Loaded ${src}, cached: ${isCached}`)}
onError={(error) => console.error("SVG failed to load:", error)}
>
<img src="/fallback-logo.png" alt="React" />
</InlineSVG>
</main>
);
}react-inlinesvg is built around several key components:
InlineSVG component handles SVG loading, processing, and renderingCore SVG loading functionality that fetches, processes, and renders SVG content inline as React elements. Supports multiple source types and provides comprehensive customization options.
declare const InlineSVG: React.FC<Props>;
interface Props extends Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {
/** SVG source - URL, base64 data URI, or raw SVG string */
src: string;
/** URL prefix for relative IDs when using uniquifyIDs */
baseURL?: string;
/** Enable SVG content caching (default: true) */
cacheRequests?: boolean;
/** Fallback content for errors/unsupported browsers */
children?: React.ReactNode;
/** SVG description text (overrides existing <desc>) */
description?: string;
/** Custom fetch options for HTTP requests */
fetchOptions?: RequestInit;
/** Ref for the rendered SVG element */
innerRef?: React.Ref<SVGElement | null>;
/** Loading component while SVG fetches */
loader?: React.ReactNode;
/** Error handler callback */
onError?: ErrorCallback;
/** Success callback with src and cache status */
onLoad?: LoadCallback;
/** SVG content preprocessing function */
preProcessor?: PreProcessorCallback;
/** SVG title text (overrides existing <title>, null removes) */
title?: string | null;
/** Hash for ID uniquification (default: random 8-char) */
uniqueHash?: string;
/** Make SVG IDs unique to prevent conflicts (default: false) */
uniquifyIDs?: boolean;
}
type ErrorCallback = (error: Error | FetchError) => void;
type LoadCallback = (src: string, isCached: boolean) => void;
type PreProcessorCallback = (code: string) => string;
interface FetchError extends Error {
code: string;
errno: string;
message: string;
type: string;
}Optional browser Cache API integration for persistent SVG storage across browser sessions. Enables faster loading and offline support for cached SVGs.
import CacheProvider from "react-inlinesvg/provider";
interface CacheProviderProps {
/** React components to wrap with cache context */
children: React.ReactNode;
/** Custom cache name (default: 'react-inlinesvg') */
name?: string;
}
declare const CacheProvider: React.FC<CacheProviderProps>;import { cacheStore } from "react-inlinesvg";
interface CacheStore {
/** Cache initialization status */
readonly isReady: boolean;
/** Register ready state callback */
onReady(callback: () => void): void;
/** Retrieve cached/fetch SVG content */
get(url: string, fetchOptions?: RequestInit): Promise<string>;
/** Store SVG content in cache */
set(url: string, data: StorageItem): void;
/** Check if URL is cached and loaded */
isCached(url: string): boolean;
/** Get all cached URLs */
keys(): string[];
/** Get all cache entries */
data(): Array<Record<string, StorageItem>>;
/** Remove specific cache entry */
delete(url: string): Promise<void>;
/** Clear all cache entries */
clear(): Promise<void>;
}
interface StorageItem {
content: string;
status: Status;
}
type Status = 'idle' | 'loading' | 'loaded' | 'failed' | 'ready' | 'unsupported';Core utility functions for environment detection, string manipulation, and DOM operations.
/** Check if DOM environment is available (browser vs SSR) */
function canUseDOM(): boolean;
/** Check if environment supports inline SVG rendering */
function isSupportedEnvironment(): boolean;
/** Generate random alphanumeric string of specified length */
function randomString(length: number): string;
/** Make HTTP request with SVG content validation */
function request(url: string, options?: RequestInit): Promise<string>;
/** Async sleep utility for specified seconds */
function sleep(seconds?: number): Promise<void>;
/** Test browser support for inline SVG elements */
function supportsInlineSVG(): boolean;
/** Remove specified properties from object, returning new object */
function omit<T extends PlainObject, K extends keyof T>(
input: T,
...filter: K[]
): Omit<T, K>;/** Default cache name for browser Cache API storage */
const CACHE_NAME = 'react-inlinesvg';
/** Maximum retry attempts for cache loading operations */
const CACHE_MAX_RETRIES = 10;
/** SVG loading and processing status constants */
const STATUS = {
IDLE: 'idle',
LOADING: 'loading',
LOADED: 'loaded',
FAILED: 'failed',
READY: 'ready',
UNSUPPORTED: 'unsupported',
} as const;/** Utility type for flattening complex type definitions */
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
/** Generic object type with string keys */
type PlainObject<T = unknown> = Record<string, T>;
/** Internal component state interface */
interface State {
content: string;
element: React.ReactNode;
isCached: boolean;
status: Status;
}https://example.com/icon.svg (requires CORS support)data:image/svg+xml;base64,PHN2Zy4uLg==data:image/svg+xml,%3Csvg...%3E<svg tagThe component handles various error scenarios:
src propAll errors are passed to the onError callback and trigger fallback to children content.