DEV Community

vrauuss softwares
vrauuss softwares

Posted on • Edited on

2

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

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

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...

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay