DEV Community

vrauuss softwares
vrauuss softwares

Posted on • Edited on

How to Import SVG as React Component

How to use SVGs as React Components using Vite and TypeScript in your application.

Featured Image


1. Install vite-plugin-svgr

This plugin transforms SVG files into React components. Choose your package manager to install:

npm install --save-dev vite-plugin-svgr
Enter fullscreen mode Exit fullscreen mode
yarn add -D vite-plugin-svgr
Enter fullscreen mode Exit fullscreen mode
pnpm add -D vite-plugin-svgr
Enter fullscreen mode Exit fullscreen mode

2. Setup vite.config.ts

  • First, import the plugin:
import svgr from "vite-plugin-svgr";
Enter fullscreen mode Exit fullscreen mode
  • Next, add the plugin to your defineConfig:
svgr()
Enter fullscreen mode Exit fullscreen mode
  • The finished structure should look like this:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";

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

3. Add Types to vite-env.d.ts

  • Enable TypeScript support for SVG props like className, width, and height.
/// <reference types="vite-plugin-svgr/client" />
Enter fullscreen mode Exit fullscreen mode

4. Import with ?react suffix and use SVG as Component

  • Import the SVG file with the ?react suffix:
import Logo from "./assets/icons/logo.svg?react";
Enter fullscreen mode Exit fullscreen mode
  • Use the imported SVG as a React component:
<Logo className="fill-red-500 size-8" />
Enter fullscreen mode Exit fullscreen mode

Contact


Blog

Coming soon…


Article


References

Top comments (1)

Collapse
 
ttsoares profile image
Thomas TS

Here my vite.config.ts do not have :
import react from "@vitejs/plugin-react";
and
plugins: [svgr(), tailwindcss()],
but all is working fine...