I tried a few ways to display SVG images in React and I want to share my choice.
- Packages with SVG icon collections
-
img
tag:<img src="someSvg" alt="some text" />
- Copy/paste
svg
tag into JSX:<svg>...</svg>
- Import SVG as React component <– my choice
Advantages of using SVGs as a React component
Why did I choose to use SVGs as a React component?
- No need to install icon collections;
- I can do customization through props:
width
,height
,fill
,stroke
,strokeWith
, etc.; - I can define other styles with CSS through
className
prop; - No need to copy/paste the SVG file;
Usage with Create React App
If you use CRA you can import SVG files and use them as React component right away.
App.js
- import logo from "./logo.svg";
+ import { ReactComponent as Logo } from "./logo.svg";
import "./App.css";
function App() {
return (
<div className="App">
<header className="App-header">
- <img src={logo} alt="logo" />
+ <Logo stroke="#f60" strokeWidth={10} width={500} />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Usage without Create React App
Create React App uses SVGR behind the scenes to import SVG files as a React component, so let’s do the same now.
1 - Install the Webpack loader called @svgr/webpack
yarn add --dev @svgr/webpack
2 - Update your webpack.config.js
...
module: {
rules: [
...
// SVG loader
{
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
titleProp: true,
},
},
'file-loader',
],
},
],
},
...
NOTE: I use it in conjunction with file-loader
, in case I want to import SVG files normally.
3 - Import SVG files as React component
import { ReactComponent as SomeImage } from 'path/to/image.svg'
...
<SomeImage width={100} height={50} fill="pink" stroke="#0066ff" />
Credits
- Transform SVGs into React components — SVGR
- File Loader —
file-loader
- Cover photo by Harpal Singh on Unsplash
Conclusion
Summing it up, using SVGs as a React component allows me to easily customize my SVG icons in a snap. That’s what I want.
Top comments (3)
Hi Sandro.
We encourage the entire article to be published on DEV.to (if you have proper rights), with a linkback if appropriate. Otherwise, we recommend original material, such as an original commentary on the article. From the Terms of Use:
Posts that are simply intended to encourage readers to view an external resource are discouraged.
Thank you.
Hi Sung,
I just published the entire article.
Thank you.
Thank you, Sandro~