If youโve worked with React, you might have seen this syntax:
import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';
And wondered:
๐ค What is
ReactComponent?
๐ค How is an SVG becoming a React component?
๐ค When should we use this?
Letโs break it down step-by-step in a very simple way ๐
What Does This Syntax Mean?
import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';
๐ This means:
โImport the SVG file and use it as a React componentโ
Usage
<SomeIcon />
๐ Instead of:
<img src="some-icon.svg" />
How Does This Actually Work?
This is not plain JavaScript behavior.
๐ It is handled by your build tool (like Webpack or Vite).
Behind the Scenes
Tools like:
- SVGR (SVG to React transformer)
convert your SVG file into:
function SomeIcon(props) {
return (
<svg {...props}>
{/* SVG content */}
</svg>
);
}
๐ So your SVG becomes a React component internally
Normal SVG vs React Component
โ Traditional Way
<img src="/icon.svg" alt="icon" />
โ React Component Way
import { ReactComponent as Icon } from './icon.svg';
<Icon />
Why Use SVG as React Component?
1. Easy Styling
<Icon style={{ color: 'red', width: 50 }} />
๐ You can style it like a component
2. Dynamic Props
<Icon width={30} height={30} />
3. Better Control
You can:
- Change color
- Animate
- Add events
Add Event Handlers
<Icon onClick={() => alert('Clicked')} />
Example (Real Usage)
SVG File
<!-- icon.svg -->
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>
React Usage
import { ReactComponent as Icon } from './icon.svg';
function App() {
return <Icon width={40} height={40} />;
}
Styling with CSS
.icon {
fill: blue;
}
<Icon className="icon" />
Important Note (Color Control)
For dynamic color:
๐ SVG must use:
fill="currentColor"
๐ Then:
<Icon style={{ color: 'green' }} />
Common Mistakes
โ Using wrong import
import Icon from './icon.svg'; // โ
๐ This gives image path, not component
โ Missing configuration
๐ Works only if:
- CRA (Create React App)
- Vite (with plugin)
- Webpack configured
When It Works Automatically
Works out-of-the-box in:
- Create React App
- Vite (with SVGR plugin)
- Next.js (with config)
When to Use <img> vs Component
Use <img> when:
- Simple display
- No styling needed
Use React Component when:
- Need styling
- Need animations
- Need dynamic behavior
Interview Tip
If asked:
โWhat is
ReactComponent asin SVG import?โ
๐ Answer:
โIt converts SVG into a React component using tools like SVGR, allowing us to use it like JSX.โ
Final Summary
ReactComponentconverts SVG โ React component- Enables styling, events, and dynamic behavior
- Powered by tools like SVGR
- Better than
<img>for interactive UI
Related Articles
- CSS Variables Explained: A Complete Guide with Examples (Beginner to Advanced)
- rem vs px in CSS: Whatโs the Difference and When to Useย Each?
๐ก Found this helpful? Subscribe for simple React tips, real-world examples, and developer-friendly tutorials. Happy Coding!