Next.js Discord

Discord Forum

Inline external SVGs

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I have a problem where I need to modify (mainly the color) of external svg's, what is the best approach to inline them at the places I need them, preferably on build time. I have looked at svgr but that either didn't work for my use case or I did it wrong. I also asked chatgpt but the solution it gave was this
import { useEffect, useState } from 'react';

export default function ExternalSVG({ url }) {
  const [svgContent, setSvgContent] = useState('');

  useEffect(() => {
    async function fetchSVG() {
      const response = await fetch(url);
      const svgText = await response.text();
      setSvgContent(svgText);
    }
    fetchSVG();
  }, [url]);

  return (
    <div
      dangerouslySetInnerHTML={{ __html: svgContent }}
      style={{ width: '50px', height: '50px' }}
    />
  );
}

which I don't like because it will fetch every time (if I understand it correctly) I'd rather have it do it on build time.

Has anyone faced a similar problem?
Answered by B33fb0n3
alright, then you can import it as you are doing into an div for example and update the CSS to update the colors
View full answer

9 Replies

@Yi Lon Ma color if svg can just be changed by css
Transvaal lionOP
Yes, but not if you use the IMG tag to load it.
@Transvaal lion Yes, but not if you use the IMG tag to load it.
it looks more like you get plain html instead of an image tag (see attached)
Transvaal lionOP
That code generated by chatgpt. The code that I am currently using is this. Just load the svg via next/image but because the svg is black and white, and I want to dynamicly do something with the colors I can't use the image tag anymore.

  return (
    <Image
      unoptimized
      width={16}
      height={16}
      src={svg_url}
      alt={description}
      className={cn("h-4 w-4", className)}
    />
  );
Answer
Transvaal lionOP
Yes, I did it. Kinda was hoping I do not have to fetch them. But well, it's working now. THanks!
sure thing