or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

caching.mdindex.md
tile.json

tessl/npm-react-inlinesvg

An SVG loader for React that enables inline SVG rendering with caching and preprocessing capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-inlinesvg@4.2.x

To install, run

npx @tessl/cli install tessl/npm-react-inlinesvg@4.2.0

index.mddocs/

react-inlinesvg

react-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.

Package Information

  • Package Name: react-inlinesvg
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install react-inlinesvg

Core Imports

import 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");

Basic Usage

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>
  );
}

Architecture

react-inlinesvg is built around several key components:

  • Main Component: InlineSVG component handles SVG loading, processing, and rendering
  • Caching System: Automatic in-memory caching with optional browser Cache API persistence
  • SVG Processing: Content preprocessing, ID uniquification, and DOM conversion
  • Error Handling: Comprehensive error handling with fallback content support
  • Loading States: Built-in loading state management with customizable loader components

Capabilities

SVG Loading and Rendering

Core 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;
}

Persistent Caching

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>;

Persistent Caching

Global Cache Store

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';

Utility Functions

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>;

Constants and Configuration

/** 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;

Additional Types

/** 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;
}

Supported SVG Sources

  • Remote URLs: https://example.com/icon.svg (requires CORS support)
  • Base64 Data URIs: data:image/svg+xml;base64,PHN2Zy4uLg==
  • URL-encoded Data URIs: data:image/svg+xml,%3Csvg...%3E
  • Raw SVG Strings: Any string containing <svg tag
  • Local Files: Relative or absolute paths (in compatible environments)

Error Handling

The component handles various error scenarios:

  • Network Failures: HTTP errors, CORS issues, timeout
  • Invalid Content: Non-SVG content, malformed SVG
  • Browser Support: Unsupported SVG features
  • Missing Source: Empty or undefined src prop
  • Conversion Errors: DOM parsing or React conversion failures

All errors are passed to the onError callback and trigger fallback to children content.