Next.js: Importing and Resizing SVGs in Styled Components
If you're using SVGs in your Next.js project with styled-components, you may encounter issues with importing and resizing images. I was personally surprised by this problem.
Example: Next.js: Remove view box
I started by using the same method I was accustomed to in Create React App (CRA), but I immediately ran into an issue with SVG support in Next.js. Fortunately, there was a quick solution: dangerously-allow-svg. My typing.d.ts file looked like this:
import React from 'react';
declare module '*.svg' {
const src: string;
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
export default src;
}
I searched for a solution to import and resize SVGs in my project. Although I found several approaches that worked, none suited my specific needs.
Unsuccessful solutions for my use case:
After a few hours of research, I discovered that the default option for removeViewBox is set to true. This caused the viewport of the SVG to revert to its default state whenever I changed the height or width.
The solution is to modify the Webpack configuration in next.config.js and set removeViewBox to false. This will allow SVG resizing to work properly.
Here’s the Webpack configuration:
function webpack(config) {
config.module.rules.push({
loader: '@svgr/webpack',
options: {
prettier: false,
svgo: true,
svgoConfig: {
plugins: [{
name: 'preset-default',
params: {
overrides: { removeViewBox: false },
},
},
],
},
titleProp: true,
},
test: /\.svg$/,
});
return config;
}
Note
If you're using .babelrc with inline-react-svg, this solution will not work for you.