Next.js Discord

Discord Forum

When using Image, and the src is SVG, fill color doesn't work

Unanswered
Ghost ant posted this in #help-forum
Open in Discord
Ghost antOP
is behavior expected or there is a workaround?

9 Replies

Western paper wasp
You can’t change the fill color of SVGs that are loaded as images. You can only use CSS on SVGs that are part of the same document (e.g. inline)
this is a browser restriction, not a next.js restriction
@Western paper wasp You can’t change the `fill` color of SVGs that are loaded as images. You can only use CSS on SVGs that are part of the same document (e.g. inline)
West African Lion
If I have several SVGs, does it mean I need to create a React component for each SVG? What other options do I have for using it inline? I need to control the SVG directly (stroke color, width, background, fill etc.)
Western paper wasp
If you use the svgr webpack plugin it’ll automatically import .svg files as react components
West African Lion
So I saw an article about that, but haven't been able to get it working. I only found guides for NextJS 13, and I'm on 14. Did 14 break compatibility?
West African Lion
this is my next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack(config) {
    // Grab the existing rule that handles SVG imports
    const fileLoaderRule = config.module.rules.find((rule) =>
      rule.test?.test?.(".svg")
    );

    config.module.rules.push(
      // Reapply the existing rule, but only for svg imports ending in ?url
      {
        ...fileLoaderRule,
        test: /\.svg$/i,
        resourceQuery: /url/, // *.svg?url
      },
      // Convert all other *.svg imports to React components
      {
        test: /\.svg$/i,
        issuer: fileLoaderRule.issuer,
        resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
        use: ["@svgr/webpack"],
      }
    );

    // Modify the file loader rule to ignore *.svg, since we have it handled now.
    fileLoaderRule.exclude = /\.svg$/i;

    return config;
  },
};

export default nextConfig;
@Western paper wasp If you use the svgr webpack plugin it’ll automatically import `.svg` files as react components
West African Lion
Here is the current code - https://github.com/EladKarni/aac-ipad-app
Any help you can provide would be greatly appreciated
Western paper wasp
what doesn’t work about it