There are multiple approaches you can take when it comes to displaying SVG images:
- Utilizing Webpack with
@svgr/webpack
- Using Babel with
babel-plugin-inline-react-svg
- Working with Next.js Image and using
Dangerously Allow SVG
in your next.config.js
(although not recommended)
First and foremost, ensure that your SVG image is fillable. There are various resources available online to help guide you through this process.
Applies to each approach below (not repeated for spacing saving)
Incorporate the following code into the file where you want the SVG to be displayed
import Star from './star.svg'
const Example = () => (
<div>
// specify fill color and stroke is optional
<Star height="100" width="100" fill="#6973ff" stroke="black" />
</div>
)
Webpack (highly recommended)
A demonstration of this approach can be found on Codesandbox here
Code snippet sourced from react-svgr documentation
- Install
yarn add --dev @svgr/webpack
- Add the following to your
next.config.js
file:
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack'],
})
return config
},
}
- Refer to the code under In the file you want the SVG to show
Babel
Code snippet taken from the plugin repository
yarn add -D babel-plugin-inline-react-svg
Add the following to your .babelrc
file:
{
"plugins": [
"inline-react-svg"
]
}
- Refer to the code under In the file you want the SVG to show
Next.js Image (Not recommended)
Here's an excerpt from Next.js explaining why this approach is not ideal:
The default loader does not optimize SVG images for several reasons. SVG is a vector format that can be resized losslessly, and it shares many features with HTML/CSS, which can pose security risks without proper Content Security Policy (CSP) headers.
Due to this information from Next.js, I will skip providing an example for this method as it overlaps with other recommended approaches.
If you still wish to explore this option, you can refer to their documentation.