• Stars
    star
    1,249
  • Rank 37,617 (Top 0.8 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An SVG loader component for ReactJS

react-inlinesvg

NPM version CI Maintainability Test Coverage

Load inline, local or remote SVGs in your React components.

View the demo

Highlights

  • 🏖 Easy to use: Just set the src
  • 🛠 Flexible: Personalize the options to fit your needs
  • ⚡️ Smart: Async requests will be cached.
  • 🚀 SSR: Render a loader until the DOM is available
  • 🟦 Typescript: Nicely typed

Usage

npm i react-inlinesvg

And import it into your code:

import React from 'react';
import SVG from 'react-inlinesvg';

export default function App() {
  return (
    <main>
      <SVG
        src="https://cdn.svgporn.com/logos/react.svg"
        width={128}
        height="auto"
        title="React"
      />
    </main>
  );
}

Props

src {string} - required.
The SVG file you want to load. It can be a require, URL or a string (base64 or url encoded). If you are using create-react-app and your file resides in the public directory you can use the path directly without require.

baseURL {string}
An URL to prefix each ID in case you are using the <base> tag and uniquifyIDs.

children {ReactNode}
The fallback content in case of a fetch error or unsupported browser.

<SVG src="...">
	<img src="..." alt="fallback" />
</SVG>

cacheRequests {boolean} ▶︎ true
Cache remote SVGs.

description {string}
A description for your SVG. It will override an existing <desc> tag.

fetchOptions {RequestInit}
Custom options for the request.

innerRef {React.Ref}
Set a ref in SVGElement.

loader {node}
A component to be shown while the SVG is loading.

onError {function}
A callback to be invoked if loading the SVG fails.
This will receive a single argument with:

  • a FetchError with:
{
  message: string;
  type: string;
  errno: string;
  code: string;
}
  • or an InlineSVGError, which has the following properties:
{
  name: 'InlineSVGError';
  data: object; // optional
  message: string;
}

onLoad {function}.
A callback to be invoked upon successful load.
This will receive 2 arguments: the src prop and a hasCache boolean

preProcessor {function} ▶︎ string
A function to process the contents of the SVG text before parsing.

title {string | null}
A title for your SVG. It will override an existing <title> tag.
If null is passed, the <title> tag will be removed.

uniqueHash {string} ▶︎ a random 8 characters string [A-Za-z0-9]
A string to use with uniquifyIDs.

uniquifyIDs {boolean} ▶︎ false
Create unique IDs for each icon.

Any additional props will be passed down to the SVG element.

Example

<SVG
  baseURL="/home"
  cacheRequests={true}
  description="The React logo"
  loader={<span>Loading...</span>}
  onError={(error) => console.log(error.message)}
  onLoad={(src, hasCache) => console.log(src, hasCache)}
  preProcessor={(code) => code.replace(/fill=".*?"/g, 'fill="currentColor"')}
  src="https://cdn.svgporn.com/logos/react.svg"
  title="React"
  uniqueHash="a1f8d1"
  uniquifyIDs={true}
/>

Caching

The internal cache is exported as cacheStore if you need to debug or pre-cache some files.
⚠️ Use it at your own risk.

Browser Support

Any browsers that support inlining SVGs and fetch will work.

If you need to support legacy browsers you'll need to include a polyfiil for fetch and Number.isNaN in your app. Take a look at react-app-polyfill or polyfill.io.

CORS

If you are loading remote SVGs, you'll need to make sure it has CORS support.

Why you need this package?

One of the reasons SVGs are awesome is because you can style them with CSS. Unfortunately, this winds up not being too useful in practice because the style element has to be in the same document. This leaves you with three bad options:

  1. Embed the CSS in the SVG document
    • Can't use your CSS preprocessors (LESS, SASS)
    • Can't target parent elements (button hover, etc.)
    • Makes maintenance difficult
  2. Link to a CSS file in your SVG document
    • Sharing styles with your HTML means duplicating paths across your project, making maintenance a pain
    • Not sharing styles with your HTML means extra HTTP requests (and likely duplicating paths between different SVGs)
    • Still can't target parent elements
    • Your SVG becomes coupled to your external stylesheet, complicating reuse.
  3. Embed the SVG in your HTML
    • Bloats your HTML
    • SVGs can't be cached by browsers between pages.
    • A maintenance nightmare

But there's an alternative that sidesteps these issues: load the SVG with a GET request and then embed it in the document. This is what this component does.

Note

The SVG <use> element can be used to achieve something similar to this component. See this article for more information and this table for browser support and caveats.

Credits

Thanks to @matthewwithanm for creating this component and so kindly transfer it to me. I'll definitely keep the good work! ❤️

More Repositories

1

logos

A huge collection of SVG logos
SVG
6,086
star
2

react-joyride

Create guided tours in your apps
TypeScript
6,046
star
3

react-redux-saga-boilerplate

Starter kit with react-router, react-helmet, redux, redux-saga and styled-components
TypeScript
607
star
4

react-spotify-web-playback

A simple player for Spotify's web playback
TypeScript
291
star
5

react-floater

Advanced tooltips for React
TypeScript
189
star
6

disable-scroll

Prevent page scrolling
TypeScript
143
star
7

react-redux-observables-boilerplate

Starter kit for React with Router, Redux, Observable + RxJS
JavaScript
89
star
8

react-redux-starter

React starter kit with redux and react-router
JavaScript
68
star
9

alfred-workflows

Collection of Alfred workflows
PHP
33
star
10

react-from-dom

Convert HTML/XML source code or DOM nodes to React elements
TypeScript
25
star
11

codeclimate-stylelint

A Code Climate engine for the mighty, modern CSS linter
Less
24
star
12

tree-changes

Compare changes between two datasets
TypeScript
21
star
13

styled-minimal

Minimal UI theme with styled-components
JavaScript
18
star
14

is-lite

Type check tool
TypeScript
17
star
15

Turntable.fm-Playlists

Add playlists to turntable.fm
JavaScript
16
star
16

react-joyride-demo

Demo for React-Joyride
TypeScript
15
star
17

components

A collection of imperfect React components
TypeScript
15
star
18

react-web-session

Keep user data between visits
TypeScript
12
star
19

mdn-search

Search MDN with Alfred 2
PHP
11
star
20

generator-web

Generate a front-end website
JavaScript
11
star
21

colormeup

a tool to inspect a color and play with its many variations
JavaScript
10
star
22

helpers

Collection of useful functions
TypeScript
9
star
23

colorizr

Color conversion, manipulation, comparison and analysis
TypeScript
8
star
24

cpf-cnpj-generator

Generate fake brazilian CPF and CNPJ
PHP
8
star
25

hooks

Collection of useful React hooks
TypeScript
7
star
26

object-to-dot-notation

Convert simple objects to dot notation
TypeScript
6
star
27

links

Useful links for development
5
star
28

cloudinary

A tiny alternative to cloudinary-npm
JavaScript
5
star
29

react-starter

React starter kit with flux, router and bootstrap with a Hacker News reader
JavaScript
4
star
30

resume-v1

Developer Resume
ApacheConf
4
star
31

react-range-slider

A range slider component for React
TypeScript
4
star
32

genpass-alfred

Generate passwords from strings
JavaScript
3
star
33

dotfiles

sensible hacker default for macOS
Vim Script
3
star
34

git-rev-webpack-plugin

Webpack plugin to use git branch, hash and tag as substitutions for file names
Shell
3
star
35

s3-api

JavaScript
3
star
36

react-bot

A guided chat for interviewing users
3
star
37

deep-equal

Lightweight deep equal comparator
TypeScript
3
star
38

web-session

Keep user sessions between visits
TypeScript
3
star
39

idea-settings

IDEA Settings
2
star
40

tsconfig

Shared Typescript config
2
star
41

crashplan-control

Control CrashPlan with Alfred
Shell
2
star
42

types

Reusable typescript typings
TypeScript
2
star
43

git-hooks

A collection of useful git hooks
Shell
2
star
44

js-codemod

Codemod scripts to transform code
JavaScript
2
star
45

hadio

Airtime custom player
JavaScript
1
star
46

react-celebration

1
star
47

big-list

Technologies that you should learn (or at least now what it is about)
1
star
48

cookies

Lightweight cookie client
TypeScript
1
star
49

react-money

1
star
50

prettier-config

Shared Prettier config
1
star
51

learning

Books, courses and presentations that I've engaged.
1
star
52

react-party

It's a party
1
star
53

github-labels

1
star
54

eslint-config

Shared ESLint config
JavaScript
1
star
55

ttRoomie

A lightweight Users List for turntable.fm
JavaScript
1
star
56

gilbarbara.github.io

My Resume
ApacheConf
1
star
57

react-dropdown

Flexible dropdown component for React
TypeScript
1
star
58

wabi-sabi

1
star
59

fluxy

Flux Playground
JavaScript
1
star
60

react-floater-demo

Demo for react-floater
TypeScript
1
star
61

simple-react-router-redux

Tiny redux bindings for react-router
JavaScript
1
star
62

raycast-extensions

Raycast Extensions
TypeScript
1
star
63

TT-Bot

room bot and dj queue manager for turntable.fm
JavaScript
1
star
64

repo-tools

Useful CLI commands for working with remote repositories.
TypeScript
1
star
65

bitbar-plugins

BitBar plugins
JavaScript
1
star
66

kollectiv-syntax

Another dark theme with cool colors
CSS
1
star
67

intera-demo

Demo for Intera
TypeScript
1
star
68

wc14

World Cup 2014
JavaScript
1
star
69

requird

Wordpress plugin to require users to fill selected fields before posting.
PHP
1
star
70

generator-marionette-2

A Marionette 2 generator for Yeoman
JavaScript
1
star
71

little-alchemy-helper

Little Alchemy Helper - Interactive app with a bookmarklet to help while you play the game Little Alchemy.
JavaScript
1
star