or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# react-inlinesvg

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: react-inlinesvg

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install react-inlinesvg`

10

11

## Core Imports

12

13

```typescript

14

import InlineSVG from "react-inlinesvg";

15

```

16

17

With types and utilities:

18

19

```typescript

20

import InlineSVG, {

21

Props,

22

ErrorCallback,

23

LoadCallback,

24

PreProcessorCallback,

25

FetchError,

26

StorageItem,

27

Status,

28

State,

29

PlainObject,

30

Simplify,

31

cacheStore,

32

canUseDOM,

33

isSupportedEnvironment,

34

randomString,

35

request,

36

sleep,

37

supportsInlineSVG,

38

omit,

39

CACHE_NAME,

40

CACHE_MAX_RETRIES,

41

STATUS

42

} from "react-inlinesvg";

43

```

44

45

For CommonJS:

46

47

```javascript

48

const InlineSVG = require("react-inlinesvg");

49

```

50

51

## Basic Usage

52

53

```typescript

54

import React from "react";

55

import InlineSVG from "react-inlinesvg";

56

57

export default function App() {

58

return (

59

<main>

60

<InlineSVG

61

src="https://cdn.svgporn.com/logos/react.svg"

62

width={128}

63

height="auto"

64

title="React Logo"

65

onLoad={(src, isCached) => console.log(`Loaded ${src}, cached: ${isCached}`)}

66

onError={(error) => console.error("SVG failed to load:", error)}

67

>

68

<img src="/fallback-logo.png" alt="React" />

69

</InlineSVG>

70

</main>

71

);

72

}

73

```

74

75

## Architecture

76

77

react-inlinesvg is built around several key components:

78

79

- **Main Component**: `InlineSVG` component handles SVG loading, processing, and rendering

80

- **Caching System**: Automatic in-memory caching with optional browser Cache API persistence

81

- **SVG Processing**: Content preprocessing, ID uniquification, and DOM conversion

82

- **Error Handling**: Comprehensive error handling with fallback content support

83

- **Loading States**: Built-in loading state management with customizable loader components

84

85

## Capabilities

86

87

### SVG Loading and Rendering

88

89

Core SVG loading functionality that fetches, processes, and renders SVG content inline as React elements. Supports multiple source types and provides comprehensive customization options.

90

91

```typescript { .api }

92

declare const InlineSVG: React.FC<Props>;

93

94

interface Props extends Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> {

95

/** SVG source - URL, base64 data URI, or raw SVG string */

96

src: string;

97

/** URL prefix for relative IDs when using uniquifyIDs */

98

baseURL?: string;

99

/** Enable SVG content caching (default: true) */

100

cacheRequests?: boolean;

101

/** Fallback content for errors/unsupported browsers */

102

children?: React.ReactNode;

103

/** SVG description text (overrides existing <desc>) */

104

description?: string;

105

/** Custom fetch options for HTTP requests */

106

fetchOptions?: RequestInit;

107

/** Ref for the rendered SVG element */

108

innerRef?: React.Ref<SVGElement | null>;

109

/** Loading component while SVG fetches */

110

loader?: React.ReactNode;

111

/** Error handler callback */

112

onError?: ErrorCallback;

113

/** Success callback with src and cache status */

114

onLoad?: LoadCallback;

115

/** SVG content preprocessing function */

116

preProcessor?: PreProcessorCallback;

117

/** SVG title text (overrides existing <title>, null removes) */

118

title?: string | null;

119

/** Hash for ID uniquification (default: random 8-char) */

120

uniqueHash?: string;

121

/** Make SVG IDs unique to prevent conflicts (default: false) */

122

uniquifyIDs?: boolean;

123

}

124

125

type ErrorCallback = (error: Error | FetchError) => void;

126

type LoadCallback = (src: string, isCached: boolean) => void;

127

type PreProcessorCallback = (code: string) => string;

128

129

interface FetchError extends Error {

130

code: string;

131

errno: string;

132

message: string;

133

type: string;

134

}

135

```

136

137

### Persistent Caching

138

139

Optional browser Cache API integration for persistent SVG storage across browser sessions. Enables faster loading and offline support for cached SVGs.

140

141

```typescript { .api }

142

import CacheProvider from "react-inlinesvg/provider";

143

144

interface CacheProviderProps {

145

/** React components to wrap with cache context */

146

children: React.ReactNode;

147

/** Custom cache name (default: 'react-inlinesvg') */

148

name?: string;

149

}

150

151

declare const CacheProvider: React.FC<CacheProviderProps>;

152

```

153

154

[Persistent Caching](./caching.md)

155

156

## Global Cache Store

157

158

```typescript { .api }

159

import { cacheStore } from "react-inlinesvg";

160

161

interface CacheStore {

162

/** Cache initialization status */

163

readonly isReady: boolean;

164

/** Register ready state callback */

165

onReady(callback: () => void): void;

166

/** Retrieve cached/fetch SVG content */

167

get(url: string, fetchOptions?: RequestInit): Promise<string>;

168

/** Store SVG content in cache */

169

set(url: string, data: StorageItem): void;

170

/** Check if URL is cached and loaded */

171

isCached(url: string): boolean;

172

/** Get all cached URLs */

173

keys(): string[];

174

/** Get all cache entries */

175

data(): Array<Record<string, StorageItem>>;

176

/** Remove specific cache entry */

177

delete(url: string): Promise<void>;

178

/** Clear all cache entries */

179

clear(): Promise<void>;

180

}

181

182

interface StorageItem {

183

content: string;

184

status: Status;

185

}

186

187

type Status = 'idle' | 'loading' | 'loaded' | 'failed' | 'ready' | 'unsupported';

188

```

189

190

### Utility Functions

191

192

Core utility functions for environment detection, string manipulation, and DOM operations.

193

194

```typescript { .api }

195

/** Check if DOM environment is available (browser vs SSR) */

196

function canUseDOM(): boolean;

197

198

/** Check if environment supports inline SVG rendering */

199

function isSupportedEnvironment(): boolean;

200

201

/** Generate random alphanumeric string of specified length */

202

function randomString(length: number): string;

203

204

/** Make HTTP request with SVG content validation */

205

function request(url: string, options?: RequestInit): Promise<string>;

206

207

/** Async sleep utility for specified seconds */

208

function sleep(seconds?: number): Promise<void>;

209

210

/** Test browser support for inline SVG elements */

211

function supportsInlineSVG(): boolean;

212

213

/** Remove specified properties from object, returning new object */

214

function omit<T extends PlainObject, K extends keyof T>(

215

input: T,

216

...filter: K[]

217

): Omit<T, K>;

218

```

219

220

## Constants and Configuration

221

222

```typescript { .api }

223

/** Default cache name for browser Cache API storage */

224

const CACHE_NAME = 'react-inlinesvg';

225

226

/** Maximum retry attempts for cache loading operations */

227

const CACHE_MAX_RETRIES = 10;

228

229

/** SVG loading and processing status constants */

230

const STATUS = {

231

IDLE: 'idle',

232

LOADING: 'loading',

233

LOADED: 'loaded',

234

FAILED: 'failed',

235

READY: 'ready',

236

UNSUPPORTED: 'unsupported',

237

} as const;

238

```

239

240

## Additional Types

241

242

```typescript { .api }

243

/** Utility type for flattening complex type definitions */

244

type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};

245

246

/** Generic object type with string keys */

247

type PlainObject<T = unknown> = Record<string, T>;

248

249

/** Internal component state interface */

250

interface State {

251

content: string;

252

element: React.ReactNode;

253

isCached: boolean;

254

status: Status;

255

}

256

```

257

258

## Supported SVG Sources

259

260

- **Remote URLs**: `https://example.com/icon.svg` (requires CORS support)

261

- **Base64 Data URIs**: `data:image/svg+xml;base64,PHN2Zy4uLg==`

262

- **URL-encoded Data URIs**: `data:image/svg+xml,%3Csvg...%3E`

263

- **Raw SVG Strings**: Any string containing `<svg` tag

264

- **Local Files**: Relative or absolute paths (in compatible environments)

265

266

## Error Handling

267

268

The component handles various error scenarios:

269

270

- **Network Failures**: HTTP errors, CORS issues, timeout

271

- **Invalid Content**: Non-SVG content, malformed SVG

272

- **Browser Support**: Unsupported SVG features

273

- **Missing Source**: Empty or undefined `src` prop

274

- **Conversion Errors**: DOM parsing or React conversion failures

275

276

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