Home > Software engineering >  Should we use SVG as React Component or use it with the image tag
Should we use SVG as React Component or use it with the image tag

Time:01-10

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 preffer using them as a component but the other guy I am working with uses it in image tag.

CodePudding user response:

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.

CodePudding user response:

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>

  • Related