日本語

How to Import SVG as a React Component in Vite

​​React​SVG,SVGR,TypeScript,Vite,vite-plugin-svgr

When you import an SVG file in a Vite React project, you get a URL string, not a component. If you want to write <BellIcon />, match the icon color to the text color, or change its size with props, install vite-plugin-svgr and add ?react to the end of the import path.

I created a project with the react-ts template from npm create vite, added a line-drawn bell icon and a solid black circle badge icon, and checked the results of the type check, the dev server, and the build.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used Vite 8.3.8, @vitejs/plugin-react 6.3.0, React 19.3.1, TypeScript 7.0.2, and vite-plugin-svgr 5.2.0 (which uses @svgr/core 8.1.0 internally). I used Playwright 1.63.0 to check the rendering. I did not test Firefox, Safari, screen reader output, or a setup that loads SVGs without ?react (changing include).

With Vite alone, an SVG is loaded as a URL

When Vite imports a file such as an image, it returns the URL of that file. As described in Vite's static asset guide, SVG files are handled the same way.

tsx
import bellUrl from './icons/bell.svg'

// bellUrl is a string. Pass it to the src of <img>.
<img src={bellUrl} alt="通知" width={48} height={48} />

The bell icon I tested was 259 bytes. After a build, no SVG file appeared in dist/assets. Instead, the SVG was embedded in the JavaScript as a data URL like data:image/svg+xml,%3csvg%20xmlns=.... This is because files smaller than the default build.assetsInlineLimit of 4096 bytes (4 KiB) are inlined instead of being written as separate files.

With an SVG shown through <img>, the page's CSS cannot change the lines or fills inside it. Even when the icon SVG has stroke="currentColor", the parent's color does not reach it, and the icon stayed black (see the first row of the image shown later).

What happens with ?react and no plugin

If you add ?react to the import before installing vite-plugin-svgr, the type check fails first.

tsx
import BellIcon from './icons/bell.svg?react'
text
$ npx tsc -b
src/App.tsx(1,22): error TS2307: Cannot find module './icons/bell.svg?react' or its corresponding type declarations.

If I skipped the type check and ran only npx vite build, the build succeeded. When I opened the page with the dev server, nothing was displayed, and the browser showed this error (the middle of the data URL is omitted):

text
Failed to execute 'createElement' on 'Document': The tag name provided ('data:image/svg+xml,%3csvg%20xmlns=...%3c/svg%3e') is not a valid name.

Nothing handles ?react, so BellIcon receives a URL string. React then tries to create an element using that string as a tag name, and this fails.

Install and configure vite-plugin-svgr

vite-plugin-svgr is a plugin that lets Vite use SVGR, which converts SVG files into React components. Install it as a dev dependency.

bash
npm install -D vite-plugin-svgr

Add svgr() to plugins in vite.config.ts.

ts
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import svgr from 'vite-plugin-svgr'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), svgr()],
})

This alone was not enough. TypeScript still did not know the type of paths ending in ?react, so the same TS2307 error remained. The vite-plugin-svgr README suggests adding /// <reference types="vite-plugin-svgr/client" /> to vite-env.d.ts.

The template I used had no vite-env.d.ts, but tsconfig.app.json listed vite/client in types. According to Vite's documentation, when types is specified, only the entries listed there are loaded as global types. So I added vite-plugin-svgr/client to the same array.

json
"types": ["vite/client", "vite-plugin-svgr/client"],

After this change, the error from npx tsc -b disappeared. The declarations in vite-plugin-svgr/client type *.svg?react imports as function components that accept the props of an <svg> element (plus title and similar).

Change the size and color with props and CSS

After installing the plugin, you can use an SVG imported with ?react like any other component.

tsx
import BellIcon from './icons/bell.svg?react'

<BellIcon />
<BellIcon width={48} height={48} />
<BellIcon className="icon" />

Looking at the transformed code from the dev server, ...props was placed after the attributes taken from the SVG file.

js
const SvgBell = (props) => /* @__PURE__ */ _jsxs("svg", {
	xmlns: "http://www.w3.org/2000/svg",
	width: 24,
	height: 24,
	viewBox: "0 0 24 24",
	fill: "none",
	stroke: "currentColor",
	...
	...props,
	children: [/* @__PURE__ */ _jsx("path", { d: "M6 16V11a6 6 0 0 1 12 0v5l2 2H4z" }), /* @__PURE__ */ _jsx("path", { d: "M10 21h4" })]
});

(Lines such as strokeWidth are omitted.)

As a result, props you pass take priority over the values written in the SVG file. <BellIcon /> with no props displayed at the 24×24 pixels defined in the file, and width={48} height={48} displayed it at 48×48 pixels. When I passed a className and set width: 48px; height: 48px; in CSS, the icon was also 48×48 pixels, so the CSS overrode the width="24" attribute.

For color, if the SVG uses currentColor, the parent's color applies directly. When I set color: #d85878 on the parent element, the bell's lines were drawn in that same pink.

Three rows comparing the icons. In all three, the parent element's color is pink. The first row is the bell shown with img and stays black. The second row is the bell as BellIcon, with pink lines. The third row is BadgeIcon, where fill="#000000" was replaced with currentColor, so its fill is pink
The same parent color gives different results for img and for components

If an SVG has a fixed fill color, use replaceAttrValues to change it to currentColor

Even as a component, if the SVG has a color written directly, such as fill="#000000", changing the parent's color does not change that color. In my test, the badge icon's circle stayed black even when the parent was pink.

Instead of editing each SVG file by hand, you can use SVGR's replaceAttrValues to replace values during conversion. With vite-plugin-svgr, you set it in svgrOptions.

ts
svgr({
  svgrOptions: {
    replaceAttrValues: { '#000000': 'currentColor' },
  },
}),

In the transformed code, the circle's fill became "currentColor", and the white checkmark's stroke: "#ffffff" was unchanged. On the page, only the circle changed to the parent's pink (the third row of the image above).

Give icons an accessible name

For decorative icons next to button text, pass aria-hidden="true" to hide them from screen readers. For icons that convey meaning alone, pass role="img" and aria-label. In the Chromium accessibility tree, the results looked like this:

text
- paragraph:
  - button "通知"
  - img "通知があります"
  - img "通知"

The third line is an icon passed title="通知". title is included in the props type, but with the default settings it was output as an attribute on the svg element, as in <svg title="通知">. The Chromium tree showed it as img "通知", but it did not become an SVG <title> element. If you want to set the name with a <title> element, set SVGR's titleProp to true.

ts
svgr({
  svgrOptions: {
    titleProp: true,
  },
}),

With this setting, writing <BellIcon title="通知" /> produced <svg ...><title>通知</title><path .../>...</svg>, with a <title> element inside.

After a build, the SVG is included in JavaScript as component code

An SVG loaded with ?react does not appear as an SVG file in dist/assets after a build. It is included in a JavaScript file as component code that contains the d attribute values of the paths (such as M6 16V11…).

text
$ ls dist/assets
index-CPOT8Xb7.js
index-d7fNLeU5.css

When I opened the build with vite preview, the icons rendered, and the accessibility tree matched the dev server. There were no browser errors. You can also import the same SVG both as a URL for <img> and as a component. In that case, both the data URL and the component code end up in the JavaScript.

​Posted by 86