DEV Community

Cover image for Reusing SVG elements in HTML without copy-pasting it
Bartłomiej Stefański
Bartłomiej Stefański

Posted on • Originally published at bstefanski.com

3 1

Reusing SVG elements in HTML without copy-pasting it

Sometimes you might encounter the case where you want to use the same SVGs multiple times across one page. The first example that comes to my mind is the use of social media icons both in the navbar and footer. This is how I would approach this

function SomePage() {  
 return (  
    // Invisible symbol  
    <svg style={{ display: "none" }} version="2.0">  
      <defs>  
        <symbol id="linkedin-badge">  
          /* This is where you would put the contents of the SVG 
          (everything that is inside SVG tag except the tag itself)  */
        </symbol>  
      </defs>  

      <use href="#linkedin-badge" />  
    </svg>   


    // And this is how you would use it  
    <svg  
      width="32"  
      height="32"  
      viewBox="0 0 32 32"  
      version="2.0"  
    >  
      <use href="#linkedin-badge" />  
    </svg>  
  )    
}
Enter fullscreen mode Exit fullscreen mode

Of course, you can just copy-paste it, but it will make the size of your HTML document bigger and delay the FCP.
You could also export it to a file, and load it through the image element, but it would cause flicks, which you probably don't want to have, especially when the element is above the fold.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay