SVGs are the best format for icons and illustrations on the web. But using them in React requires transformation. Here is everything you need to know.
The Problem
SVG uses HTML attributes that break in JSX:
| SVG Attribute | JSX Equivalent |
|---|---|
| class | className |
| stroke-width | strokeWidth |
| fill-opacity | fillOpacity |
| font-size | fontSize |
| clip-path | clipPath |
| xlink:href | xlinkHref |
SVGR: The Industry Standard
SVGR converts SVG files into React components automatically:
npx @svgr/cli icon.svg --out-dir src/icons
With Vite:
import svgr from 'vite-plugin-svgr';
export default defineConfig({ plugins: [svgr()] });
// Usage
import { ReactComponent as Logo } from './logo.svg';
Always Optimize First
Run SVGO before converting to strip metadata and redundant attributes:
npx svgo icon.svg -o icon.min.svg
Typical reduction: 30-60%.
Reusable Icon Component
const Icon = ({ size = 24, color = 'currentColor', ...props }) => (
<svg width={size} height={size} viewBox='0 0 24 24' fill='none'
stroke={color} strokeWidth={2} {...props}>
<polyline points='20 6 9 17 4 12' />
</svg>
);
Accessibility
// Meaningful icon
<svg role='img' aria-labelledby='title'>
<title id='title'>Search</title>
<path d='...' />
</svg>
// Decorative icon
<svg aria-hidden='true'><path d='...' /></svg>
Try It Online
Convert SVG to React JSX with DevToolBox SVG to JSX - handles attribute conversion, optimization, TypeScript output.
How do you manage SVGs in React? Share your approach!
Top comments (0)