Display SVG Icons in UI Using React Component

SVG icons are popular in web development because they are lightweight, scalable, and easy to style. In React, there are several simple ways to display .svg files:

1. Import SVG as a React Component

Import the SVG file directly and use it like a normal component:

Copy to clipboard
import { ReactComponent as MyIcon } from './icons/my-icon.svg';

const MyComponent = () => <MyIcon width={24} height={24} />;

Note: Supported in Create React App (CRA) and Vite (with vite-plugin-svgr).

Advantages:

  • Full styling control via props or CSS
  • Supports dynamic color changes and hover effects

2. Use SVG as an img Tag

Treat the SVG like a regular image:

Copy to clipboard
const MyComponent = () => (
  <img src="/icons/my-icon.svg" alt="My Icon" width={24} height={24} />
);

Advantages:

-> Very simple for static icons

Limitations:

-> Harder to change colors dynamically

3. Inline SVG Code Inside the Component

Paste the SVG markup into your component:

Copy to clipboard
const MyIcon = () => (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
    <path d="M12 2L2 22h20L12 2z" fill="currentColor"></path>
  </svg>
);

Advantages:

  • Full styling flexibility with CSS
  • No external file dependency

4. Dynamically Import SVG Files

Load icons based on props:

Copy to clipboard
const MyComponent = ({ iconName }: { iconName: string }) => {
  const Icon = require(`./icons/${iconName}.svg`).default;
  return <img src="{" icon="" }="" alt="{iconName}">;
};

Or with Vite:

Copy to clipboard
const icons = import.meta.glob('./icons/*.svg', { eager: true, import: 'default' });
const MyComponent = ({ iconName }: { iconName: string }) => {
  const Icon = icons[`./icons/${iconName}.svg`];
  return <img src="{" icon="" }="" alt="{iconName}">;
};

Advantages:

  • Efficient when handling many icons
  • Supports lazy loading for smaller bundles

Best Practice Recommendation

  • Dynamic and styled icons? → Import SVG as a React component.
  • Simple static icons? → Use an img tag.
  • Maximum control? → Inline the SVG.

Choose the method that fits your needs and keep your UI lightweight and flexible!

Need Help With React js Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Support On Demand!