or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

basic-shapes.mdclipping-masking.mdcontainer-elements.mdfilter-effects.mdgradients-patterns.mdindex.mdpaths-complex-shapes.mdtext-elements.mdxml-processing.md

xml-processing.mddocs/

0

# XML Processing

1

2

Utilities for loading, parsing, and rendering SVG content from XML strings and remote URIs, enabling dynamic SVG content integration.

3

4

## Capabilities

5

6

### SvgXml

7

8

Renders SVG content from XML strings with error handling and fallback support.

9

10

```typescript { .api }

11

/**

12

* Renders SVG from XML string

13

* @param xml - SVG XML string to render

14

* @param onError - Error handler function

15

* @param override - Props to override on root SVG element

16

* @param fallback - Component to render on error

17

*/

18

interface XmlProps extends SvgProps, AdditionalProps {

19

xml: string | null;

20

}

21

22

interface AdditionalProps {

23

onError?: (error: Error) => void;

24

override?: object;

25

onLoad?: () => void;

26

fallback?: JSX.Element;

27

}

28

29

declare function SvgXml(props: XmlProps): JSX.Element;

30

```

31

32

**Usage Examples:**

33

34

```typescript

35

import React, { useState } from "react";

36

import { SvgXml } from "react-native-svg";

37

38

// Basic XML rendering

39

const svgXml = `

40

<svg width="100" height="100" viewBox="0 0 100 100">

41

<circle cx="50" cy="50" r="40" fill="red" />

42

<text x="50" y="55" text-anchor="middle" fill="white">SVG</text>

43

</svg>

44

`;

45

46

function XmlExample() {

47

return (

48

<SvgXml xml={svgXml} width="100" height="100" />

49

);

50

}

51

52

// XML with error handling

53

function XmlWithErrorHandling() {

54

const [error, setError] = useState<string | null>(null);

55

56

const invalidXml = "<svg><invalid-element></svg>";

57

58

return (

59

<SvgXml

60

xml={invalidXml}

61

width="100"

62

height="100"

63

onError={(err) => setError(err.message)}

64

fallback={<Text>Failed to load SVG</Text>}

65

/>

66

);

67

}

68

69

// Override SVG properties

70

function XmlWithOverride() {

71

const xml = `<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="blue"/></svg>`;

72

73

return (

74

<SvgXml

75

xml={xml}

76

width="200"

77

height="200"

78

override={{ fill: "green" }}

79

/>

80

);

81

}

82

```

83

84

### SvgUri

85

86

Fetches and renders SVG content from remote URLs with loading states and error handling.

87

88

```typescript { .api }

89

/**

90

* Fetches and renders SVG from URI

91

* @param uri - URL to fetch SVG content from

92

* @param onError - Error handler function

93

* @param onLoad - Success callback when SVG loads

94

* @param fallback - Component to render on error

95

* @param override - Props to override on root SVG element

96

*/

97

interface UriProps extends SvgProps, AdditionalProps {

98

uri: string | null;

99

}

100

101

declare function SvgUri(props: UriProps): JSX.Element;

102

```

103

104

**Usage Examples:**

105

106

```typescript

107

import React, { useState } from "react";

108

import { SvgUri } from "react-native-svg";

109

import { ActivityIndicator, Text } from "react-native";

110

111

// Basic URI loading

112

function UriExample() {

113

return (

114

<SvgUri

115

uri="https://example.com/icon.svg"

116

width="100"

117

height="100"

118

/>

119

);

120

}

121

122

// URI with loading states

123

function UriWithLoading() {

124

const [loading, setLoading] = useState(true);

125

const [error, setError] = useState<string | null>(null);

126

127

return (

128

<>

129

{loading && <ActivityIndicator />}

130

<SvgUri

131

uri="https://example.com/logo.svg"

132

width="200"

133

height="100"

134

onLoad={() => setLoading(false)}

135

onError={(err) => {

136

setLoading(false);

137

setError(err.message);

138

}}

139

fallback={<Text>Failed to load SVG</Text>}

140

/>

141

</>

142

);

143

}

144

145

// Data URI support

146

function DataUriExample() {

147

const dataUri = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNDAiIGZpbGw9InJlZCIvPjwvc3ZnPg==";

148

149

return (

150

<SvgUri

151

uri={dataUri}

152

width="100"

153

height="100"

154

/>

155

);

156

}

157

```

158

159

### SvgAst

160

161

Renders SVG from pre-parsed Abstract Syntax Tree for performance optimization.

162

163

```typescript { .api }

164

/**

165

* Renders SVG from parsed AST

166

* @param ast - Parsed SVG AST structure

167

* @param override - Props to override on root SVG element

168

*/

169

interface AstProps extends SvgProps, AdditionalProps {

170

ast: JsxAST | null;

171

}

172

173

declare function SvgAst(props: AstProps): JSX.Element | null;

174

```

175

176

**Usage Examples:**

177

178

```typescript

179

import { SvgAst, parse } from "react-native-svg";

180

181

// Pre-parse XML for reuse

182

const svgXml = `<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="blue"/></svg>`;

183

const parsedAst = parse(svgXml);

184

185

function AstExample() {

186

return (

187

<SvgAst

188

ast={parsedAst}

189

width="100"

190

height="100"

191

/>

192

);

193

}

194

```

195

196

### Parsing Functions

197

198

Core parsing utilities for converting XML strings to renderable AST structures.

199

200

```typescript { .api }

201

/**

202

* Parses SVG XML string into JSX AST

203

* @param xml - SVG XML string to parse

204

* @returns Parsed JSX AST or null if parsing fails

205

*/

206

declare function parse(xml: string): JsxAST | null;

207

208

/**

209

* Converts kebab-case to camelCase for React props

210

* @param str - String to convert

211

* @returns CamelCase string

212

*/

213

declare function camelCase(str: string): string;

214

```

215

216

**Usage Examples:**

217

218

```typescript

219

import { parse, camelCase } from "react-native-svg";

220

221

// Parse XML to AST

222

const xmlString = `

223

<svg width="200" height="200">

224

<rect x="50" y="50" width="100" height="100" fill="green"/>

225

</svg>

226

`;

227

228

const ast = parse(xmlString);

229

console.log(ast); // JsxAST structure

230

231

// Convert attribute names

232

const converted = camelCase("stroke-width"); // "strokeWidth"

233

const converted2 = camelCase("text-anchor"); // "textAnchor"

234

```

235

236

### Utility Functions

237

238

Additional utilities for handling SVG data and URIs.

239

240

```typescript { .api }

241

/**

242

* Fetches text content from URI with support for data URIs and base64

243

* @param uri - URI to fetch from (http/https/data/file)

244

* @returns Promise resolving to text content or null

245

*/

246

declare function fetchText(uri?: string): Promise<string | null>;

247

```

248

249

**Usage Examples:**

250

251

```typescript

252

import { fetchText } from "react-native-svg";

253

254

// Fetch SVG from URL

255

async function loadSvgContent() {

256

try {

257

const svgText = await fetchText("https://example.com/icon.svg");

258

if (svgText) {

259

// Use with SvgXml

260

return svgText;

261

}

262

} catch (error) {

263

console.error("Failed to fetch SVG:", error);

264

}

265

return null;

266

}

267

268

// Handle data URIs

269

async function loadDataUri() {

270

const dataUri = "data:image/svg+xml;utf8,<svg width='100' height='100'><circle cx='50' cy='50' r='40' fill='red'/></svg>";

271

const content = await fetchText(dataUri);

272

return content; // Decoded SVG string

273

}

274

275

// Handle base64 data URIs

276

async function loadBase64Uri() {

277

const base64Uri = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCI+PGNpcmNsZSBjeD0iNTAiIGN5PSI1MCIgcj0iNDAiIGZpbGw9InJlZCIvPjwvc3ZnPg==";

278

const content = await fetchText(base64Uri);

279

return content; // Decoded SVG string

280

}

281

```

282

283

## AST Structure Types

284

285

```typescript { .api }

286

/**

287

* Base AST node structure

288

*/

289

interface AST {

290

tag: string;

291

style?: Styles;

292

styles?: string;

293

priority?: Map<string, boolean | undefined>;

294

parent: AST | null;

295

children: (AST | string)[] | (JSX.Element | string)[];

296

props: {

297

[prop: string]: Styles | string | undefined;

298

};

299

Tag: ComponentType<ComponentProps<any>>;

300

}

301

302

/**

303

* XML-specific AST node

304

*/

305

interface XmlAST extends AST {

306

children: (XmlAST | string)[];

307

parent: XmlAST | null;

308

}

309

310

/**

311

* JSX-specific AST node

312

*/

313

interface JsxAST extends AST {

314

children: (JSX.Element | string)[];

315

}

316

317

/**

318

* Style definitions

319

*/

320

interface Styles {

321

[key: string]: string | number | undefined;

322

}

323

324

/**

325

* Middleware function for processing XML

326

*/

327

type Middleware = (ast: XmlAST) => XmlAST;

328

```

329

330

## Advanced XML Processing

331

332

### Custom Error Handling

333

334

```typescript

335

function AdvancedXmlComponent() {

336

const [svgContent, setSvgContent] = useState<string | null>(null);

337

const [isLoading, setIsLoading] = useState(false);

338

const [error, setError] = useState<Error | null>(null);

339

340

const handleError = (err: Error) => {

341

console.error("SVG Error:", err);

342

setError(err);

343

// Log to analytics, show user-friendly message, etc.

344

};

345

346

return (

347

<SvgXml

348

xml={svgContent}

349

width="200"

350

height="200"

351

onError={handleError}

352

fallback={

353

<View style={{ width: 200, height: 200, justifyContent: 'center', alignItems: 'center' }}>

354

<Text>SVG could not be loaded</Text>

355

</View>

356

}

357

/>

358

);

359

}

360

```

361

362

### Dynamic SVG Loading

363

364

```typescript

365

function DynamicSvgLoader({ url }: { url: string }) {

366

const [svgData, setSvgData] = useState<string | null>(null);

367

const [loading, setLoading] = useState(true);

368

369

useEffect(() => {

370

const loadSvg = async () => {

371

try {

372

setLoading(true);

373

const data = await fetchText(url);

374

setSvgData(data);

375

} catch (error) {

376

console.error("Failed to load SVG:", error);

377

} finally {

378

setLoading(false);

379

}

380

};

381

382

loadSvg();

383

}, [url]);

384

385

if (loading) {

386

return <ActivityIndicator />;

387

}

388

389

return (

390

<SvgXml

391

xml={svgData}

392

width="100%"

393

height="200"

394

preserveAspectRatio="xMidYMid meet"

395

/>

396

);

397

}

398

```

399

400

### SVG Content Validation

401

402

```typescript

403

function validateSvgContent(xml: string): boolean {

404

try {

405

const ast = parse(xml);

406

return ast !== null && ast.tag === 'svg';

407

} catch {

408

return false;

409

}

410

}

411

412

function SafeSvgRenderer({ xml }: { xml: string }) {

413

const isValid = validateSvgContent(xml);

414

415

if (!isValid) {

416

return <Text>Invalid SVG content</Text>;

417

}

418

419

return <SvgXml xml={xml} width="100" height="100" />;

420

}

421

```