I've created a custom icon and imported it as SVG on my next.js app. I want to implement a feature where users can customize the color of this icon, like red to yellow or black, etc. But this is static image, is there a way I can achieve this?
There are a few possible ways to approach this:
@svgr/webpack
babel-plugin-inline-react-svg
Dangerously Allow SVG
in next.config.js
(Not a recommended approach)First off, your SVG image needs to be fillable. How to do this is beyond the scope of the question, but there are many resources online to help you.
In the file you want the SVG to show
import Star from './star.svg'
const Example = () => (
<div>
// set your color in fill and stroke is optional
<Star height="100" width="100" fill="#6973ff" stroke="black" />
</div>
)
I made a demo with this approach on Codesandbox
Snippet code pulled from react-svgr
yarn add --dev @svgr/webpack
next.config.js
file add the following:module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
use: ['@svgr/webpack'],
})
return config
},
}
Snippet code pulled from plugin repo
yarn add -D babel-plugin-inline-react-svg
Add following to your .babelrc
file:
{
"plugins": [
"inline-react-svg"
]
}
Excerpt from Next.js as to why you shouldn't use this approach:
The default loader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper Content Security Policy (CSP) headers.
Because of what was said from Next.js I won't be coding this example as it's redundant given the other approaches.
If you still want to follow this process you can view their documentation.