SVGR is a tool that allows you to use SVG files as React components.
With SVGR, you can pass SVGProps to your SVGs and easily reuse them in JSX.
Configuration differs depending on your build tool, but here we’ll focus on Vite.
First, install vite-plugin-svgr, then add it to your vite.config.ts:
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";
export default defineConfig({
plugins: [
react(),
svgr(), // Optional: add SVGR options if needed
],
});
TypeScript needs to recognize SVG files as React components.
The key is adding ?react to the import extension.
// vite-env.d.ts
declare module "*.svg?react" {
import * as React from "react";
const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
export default ReactComponent;
}
Now you can import and use SVGs directly in JSX:
import LogoIcon from '@/assets/icon/logo.svg?react';
const Example = () => {
return (
<>
...
<LogoIcon width={50} height={50} className="fill-current" />
</>
);
};
This approach allows you to freely control SVG attributes like width, height, fill, and stroke via props.
SVG is a vector-based format.
It can scale without losing quality and is stored as code, making it ideal for:
On the other hand, PNG, JPG, and JPEG are raster-based formats, which may lose quality when resized.