mikekubn.cz

Next.js import and resize SVG in styled components

If you want to use SVG in your Next.js project with styled components you can find problem with import and resize image. I personally surprised by this problem.

Example: Next.js with styled components resize SVG

styled components

I started the same way I was used to using in CRA, but immediately ran into an issue regarding SVG support in Next.js but it had a quick solution Dangerously Allow SVG . My typing.d.ts file looked like this:

declare module '*.svg' {
  import React from 'react';

  const src: string;

  export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
  export default src;
}

I was looking for some solution for import, resize SVG in my project. I found several solutions that works, but it no worked for my purposes.

Successful solution but neither worked for my purposes

After a few hours of researched, I discovered that the default option for removeViewBox is set to true. When I changed the height or width in the SVG, the viewport from the SVG returned to the default state. The solution is edit the webpack configuration in next.config.js and set removeViewBox to false SVG resizing will work.

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 are using .babelrc with inline-react-svg, this solution will not work for you.

Akcenta

Frontend Lead Developer
Akcenta

The beginning of the digitization of one of the biggest players in the financial market with currencies. Akcenta is Central Europe’s largest payment institution with more than 46,000, primarily B2B, clients.

Webscope.io

React senior developer
Webscope.io

Passionate about website development, app development, design, and the newest technologies we continuously deliver outstanding software solutions to our clients for over 5 years.

Arc

Arc Certified Remote Developer
Arc

Cooperation with foreign clients around the world on interesting projects

Livesport TV

React developer & QA tester
Livesport TV

Media services platform development for Livesport, that is the largest supplier of results from the world of sports in the world. You may know them from the Super Bowl. We developed SPA in React and other smaller landing websites.

Ping me.

LinkeIn
GitHub
Twitter