0

I noticed many websites like Instagram and Medium use SVG as a component for icons, and I also noticed some use SVG by putting them in image tag. I not sure which one is a good practice, and what's the advantage of using it as a component.

Generally I prefer to use them as a component but the other guy I am working with uses it in image tag.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kriptonian
  • 311
  • 1
  • 2
  • 12
  • The main difference is that using an img tag means that you can't (or can't easily) access or change the contents of the svg from outside. See answers like this for more details: https://stackoverflow.com/questions/4476526/do-i-use-img-object-or-embed-for-svg-files – aptriangle Jan 09 '23 at 11:44

2 Answers2

1

The benefit of using a svg tag is that you can style the icon with CSS. If, for example, you have multiple icons on your site and decide to change their color you could easily do this if you placed them inside svg tags. This isn't the case if you load them as the src of an img tag.

(EDIT: the tricky thing is that you have to change the fill of the path, in order to change the color of the SVG, an example is given below).

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

svg {
  width: 5rem;
}

svg path {
  fill: green;
}
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512">
      <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. -->
      <path
        d="M290.7 311L95 269.7 86.8 309l195.7 41zm51-87L188.2 95.7l-25.5 30.8 153.5 128.3zm-31.2 39.7L129.2 179l-16.7 36.5L293.7 300zM262 32l-32 24 119.3 160.3 32-24zm20.5 328h-200v39.7h200zm39.7 80H42.7V320h-40v160h359.5V320h-40z"
      />
    </svg>
  </body>
Data Moose
  • 367
  • 1
  • 6
  • 1
    Is there any performance advantage? – kriptonian Jan 09 '23 at 12:36
  • I think it depends on the context. I suspect that in most cases loading it as the source of an image tag will be slower because it requires an additional HTTP request to fetch the icon. On the other hand using an SVG tag makes the HTML file bigger so if you use lots of complex ones on a page, this might make it slower to load. I am not an expert though and would be interested in hearing what others think – Data Moose Jan 09 '23 at 14:01
0

When you say 'use as component', I assume you mean having a separate component which contains an svg tag, passing attributes as props to it? I'd say that if you regularly have to assign custom attributes/props to it, a component is useful. There's no right or wrong, just whatever works best for you.

paddotk
  • 1,359
  • 17
  • 31