Optimizing, Converting And Exporting SVG Icons In React (2023)

Optimizing, Converting And Exporting SVG Icons In React

By Roy Derks on 10 december 2020

At Vandebron we're maintaining a component library called Windmolen (Dutch for "wind turbine"). And if you've ever built a component library, you probably dealt with optimizing and converting icons before. With SVGO and SVGR you can do this at scale, without compromising the quality or size of your icons.

The problem

The web is full of icons, and often these icons are rendered from SVG files to ensure you can increase (or decrease) the size of the icons depending on the use case. Designers often create these icons from design tools like Adobe Photoshop or Sketch. Although these icons might look pretty, exporting a SVG out of these tools is often difficult as this article explains. Also, added lot of code in the form of metadata is added to the SVG file. Let's have a look at what a typical SVG file exported out of Sketch looks like:

<!-- something.svg --><?xml version="1.0" encoding="UTF-8"?><svg width="14px" height="14px" viewBox="0 0 14 14" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 46 (44423) - http://www.bohemiancoding.com/sketch --> <title>last</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="last" transform="translate(2.000000, 0.000000)" fill-rule="nonzero" fill="#666666"> <polygon id="Fill-2" points="6.6902923 9.6812703 9.3700469 7.0005052 6.6902923 4.3187297 2.37257308 0 0 2.37358354 4.3177192 6.6902923 4.6279322 7.0005052 4.3177192 7.3107182 0 11.6274269 2.37257308 14"></polygon> </g> </g></svg>

The SVG file above holds a lot of information about Sketch, such as the title of the icon and a description. Next to that, there's a lot of elements that could be combined into one element to reduce the file size.

Optimizing SVGs

What's cool about SVG files is that you can optimize and minify them, without affecting what the SVG looks like. This is something you can try out yourself using the website SVGOMG, which is powered by the library SVGO that you'll learn more about later.

(Video) Build an icon component library for React with SVGR and Rollup

You can optimize the SVG file above by following these steps:

  • Go to https://jakearchibald.github.io/svgomg/
  • Click on Paste markup an paste the SVG code that you exported from Sketch (a.k.a. the SVG file above)
  • You will see the icon rendered, now you have to either click at the Copy as a text or Download button to get the optimized SVG file

With these simple steps you've optimized the SVG from over 450 bytes, which is already small, to 173 bytes (a decrease of over 62%!). If you'd open this file in the editor of your choice, you can see a lot of the useless (meta)data from the original file has been deleted. Also, the different elements of the SVG are combined in a single path that renders the icon:

<!-- something.svg --><svg width="14" height="14" xmlns="http://www.w3.org/2000/svg"> <path d="M8.69 9.681l2.68-2.68-2.68-2.682L4.373 0 2 2.374 6.318 6.69l.31.31-.31.31L2 11.628 4.373 14z" fill-rule="nonzero" fill="#666"/></svg>

This SVG can be even further optimized by checking the "Prefer viewbox to width/height" in SVGOMG, but let's save that for later when we use SVGO instead.

Using SVGO

By using SVGOMG you've already experienced what power SVGO has, as SVGOMG is described by its creators as " SVGO's Missing GUI, aiming to expose the majority if not all the configuration options of SVGO". Instead of using the GUI, you can also use SVGO directly from the command line as a CLI-tool or as a Node.js module. For the sake of this article, we'll be using it solely as CLI.

SVGO can be installed globally on your machine, or locally in your project, from npm by running:

(Video) Optimize SVG for React Applications with Illustrator - Part 1

npm i -g svgo# Yarn equivalentyarn add -G svgo

After doing this you can run svgo from the command line and optimize any SVG file instantly. But, you don't want to do this manually on your machine anytime you're adding a new icon to a project (or component library). Therefore, you can also add SVGO to a project locally and add a script to the package.json file to optimize all SVGs in a certain directory.

// package.json{ // ... "scripts": { // ... "optimize-svg": "svgo --config=.svgo.yml -f ./src/assets/icons" }}

The optimize-svg script will run SVGO in the directory src/assets/icons and optimize all the SVG files based on the settings in .svgo.yml. This file is where you can configure the rules for SVGO, as the previously mentioned "Prefer viewbox to width/height":

# .svgo.ymlplugins: - removeViewBox: false - removeDimensions: true # this deletes width/height and adds it to the viewBox - removeDoctype: true - removeComments: true - removeMetadata: true - removeEditorsNSData: true - cleanupIDs: true - removeRasterImages: true - removeUselessDefs: true - removeUnknownsAndDefaults: true - removeUselessStrokeAndFill: true - removeHiddenElems: true - removeEmptyText: true - removeEmptyAttrs: true - removeEmptyContainers: true - removeUnusedNS: true - removeDesc: true - prefixIds: false - prefixClassNames: false

From the rules above you'll get an idea about all the redundant and useless lines of code that might be present in your SVG files. But luckily, they will all get removed when you run the command npm run optimize-svg.

Converting SVGs with SVGR

You've now learned how to optimize your SVG files, and are probably wondering how to use these files in a React application. To render an SVG in React, you need to either configure Webpack in a way that it knows how to deal with SVG files or use a library called SVGR. By default, any application created with create-react-app can render SVG files as a component, using the following import statement:

// MyComponent.jsximport React from 'react';import { ReactComponent as MySVG } from './something.svg';const MyComponent = () => { return ( <div> <MySVG /> </div> );}export default MyComponent;

More information about how this is done can be found in this article, but let me show you how to solve that with SVGR.

(Video) How to export and optimize a SVG graphic

With SVGR you can convert SVG files into React Components, either by adding it to Webpack or by using the SVGR CLI or Node.js module. In the same way, as we optimized the SVGs from the command line with SVGO, we can also convert these icons from the command line with SVGR:

// package.json{ // ... "scripts": { // ... "optimize-svg": "svgo --config=.svgo.yml -f ./src/assets/icons", "convert-svg": "svgr -d ./src/components/Icon ./src/assets/icons" }}

Whenever you run the command npm run convert-svg a JSX file will be created for every SVG file that's present in the directory src/assets/icons. These JSX files can be found in the directory src/components/Icons, together with an index.js file that exports all these components from this directory.

An example of such a converted SVG file is:

// MySVG.jsximport * as React from 'react';const MySVG = (props) => ( <svg viewBox="0 0 14 14" xmlns="http://www.w3.org/2000/svg" {...props}> <path d="M8.69 9.681l2.68-2.68-2.68-2.682L4.373 0 2 2.374 6.318 6.69l.31.31-.31.31L2 11.628 4.373 14z" fill-rule="nonzero" fill="#666"/> </svg>);export default MySVG;

And, as we now have a directory filled with converted SVGs these can be imported into any React component like this:

// MyComponent.jsximport React from 'react';import MySVG from './MySVG.jsx';const MyComponent = () => { return ( <div> <MySVG /> </div> );}export default MyComponent;

Often SVGR is used alongside SVGO, so you can even automatically optimize all SVGS that will be converted by SVGR. This is done by adding the flag --no-svgo true and point it towards your SVGO configuration file:

(Video) Optimize SVG for React Applications with Illustrator | Part 3

// package.json{ // ... "scripts": { // ... "convert-svg": "svgr -d ./src/components/Icon ./src/assets/icons --no-svgo true --svgo-config .svgo.yml" }}

By running the convert-svg script you both optimize and convert all the SVG files in src/assets/icons to React components based on optimized SVGs.

Reading further

The examples in this post are the tip of the metaphorical iceberg on what problems SVGO and SVGR can solve. There are many other features you can enable, such as using them as Node.js modules or enabling TypeScript support. To read further make sure to have a look at the SVGR playground or documentation.

(Video) Working with SVG in React and different ways of styling it

FAQs

How do I export SVG icons from React? ›

After finding the icon you want, hover over that icon, where you'll see options to copy that icon as SVG or JSX, and copy it as JSX. With that icon copied, create a new file under src called Globe. js . Inside of that file, we're going to create a new component called Globe and paste in our SVG within that component.

What is the best way to use SVG in React? ›

Importing SVGs using the image tag is one of the easiest ways to use an SVG. If you initialize your app using CRA (Create React App), you can import the SVG file in the image source attribute, as it supports it off the bat. import YourSvg from "/path/to/image.

How do I optimize an SVG file? ›

1. Use your vector graphic editor
  1. Delete invisible layers.
  2. Carefully consider converting all text to paths.
  3. Combine paths. ...
  4. Don't mask; crop by reshaping you paths and actually deleting hidden content. ...
  5. Simplify groups. ...
  6. Scan for non-SVG friendly elements such as embedded raster images.
  7. Lastly, trim your canvas.

Is it better to use SVG or PNG in React? ›

Instead of using . png or . jpeg files in your React Native app, you should be using the SVG format. SVG is a vector-based format that can scale infinitely without compromising quality.

What is the best icon library for React? ›

9 Best React Icon Libraries in 2022
  • Unicons. Get Unicons. ...
  • Font Awesome. Font Awesome is a popular icon library, with over 2,000 free and open-source icons. ...
  • React Feather. ...
  • Material UI. ...
  • Styled Icons. ...
  • IconPark. ...
  • CoreUI for React. ...
  • Iconify.
13 Sept 2022

How do you increase the size of the SVG icon in React? ›

You can change the size using CSS transform: scale(2) in <ComponentName /> , which in React can be achieved using className or a global CSS file.

How to convert SVG to React component? ›

There are several ways to integrate SVG into your React application:
  1. Use an img tag. const Star = props => ( <img src="star.svg" alt="Star" width="20" height="20" {... props} /> ...
  2. Use JSX. This solution consists of integrating the SVG directly into the React component in JSX. It has several advantages:
6 Dec 2017

Which type of SVG is mostly preferred? ›

So as XML files, you can create and edit an SVG image with text editor, but generally drawing programs like inkspace are preferred to create it. SVG is mostly used for vector type diagrams like pie charts, 2-Dimensional graphs in an X,Y coordinate system etc.

What is Optimised SVG? ›

Plain SVG is simply the SVG file from Inkscape with the Inkscape stuff removed, so it will work in any SVG editing program. Optimized SVG is: It uses the Scour python script.

Does size matter in SVG? ›

Sizing on SVG is pretty arbitrary as it is a vector format, the layout is done with maths and so isn't dependent on the size you specify. However, if the SVG is rendered on the page and then gets resized size it can make a difference at the rendering stage.

What is the best SVG editor? ›

Topmost text editors for creating SVG icons
  1. Adobe Illustrator. One of the best SVG editors for Windows and Mac, Adobe Illustrator can be your go-to SVG tool every time you need an SVG image. ...
  2. Inkscape. ...
  3. Vectr. ...
  4. Sketch. ...
  5. Gravit Designer. ...
  6. Vecteezy. ...
  7. Affinity Designer.
4 Feb 2022

What are the disadvantages of using SVG? ›

The disadvantages of SVG images
  • Cannot support as much detail. Since SVGs are based on points and paths instead of pixels, they can't display as much detail as standard image formats. ...
  • SVG doesn't work on legacy browsers. Legacy browsers, such as IE8 and lower, don't support SVG.
6 Jan 2016

Is SVG faster than image? ›

SVG code is loaded faster because there is no need for an HTTP request to load in an image file.

Which styling is best for React? ›

Inline styles are the most direct away to style any React application. Styling elements inline doesn't require you to create a separate stylesheet. Style applied directly to the elements as compared to styles in a stylesheet also have higher precedence.

Is hero or icon better? ›

The one important difference between Heroes and Icons is the ease of getting chemistry bonuses. An Icon card can always create a positive link regardless of nationality or club. FUT Hero Cards can only link up with same nationalities or leagues instead.

Do react-icons increase bundle size? ›

Carbon react icons increases bundle size when app is growing.

How import all icons in React? ›

Go to the React-icons page. You will see a number of icon libraries that you can use. Each library of icons has an import code for it.

How increase SVG width and height? ›

Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .

Why is SVG file so small? ›

SVG is just instructions on how to draw something, so if those instructions are simple enough, they can be quite a bit smaller than having to store data on each pixel. It's a bit more complex than that, as compression comes into play on both sides, but that the overall idea is there.

How do I increase icon size in React icons? ›

To increase icon sizes relative to their container, use size prop with xs , sm , lg (33% increase), or use literal sizes (to scale it from 1x to 10x) 2x , 3x , 4x , 5x , 6x , 7x , 8x , 9x , 10x . You can make all your icons the same width so they can easily vertically align, like in a list or navigation menu.

How do I stop SVG from scaling? ›

In order to avoid the no-CSS scaling issue, all you need to do is not remove the width and height attributes from the SVG.
  1. Keep the width and height attributes. ...
  2. Specify your desired width and height values in the CSS.
1 Mar 2016

How do I optimize an image size? ›

Here are six key strategies you can use to optimize image files, reduce page load time and improve the user experience.
  1. Choose the Right File Format.
  2. Use Progressive JPEG and Next-Gen File Formats.
  3. Caching.
  4. Compression.
  5. Resizing.
  6. Optimize Image Delivery.
26 May 2021

Does scaling SVG image degrade image quality? ›

Let's break this down: Scalable: SVGs can be resized up or down without damaging the quality of the image. It will be perfectly crisp and clear, no matter how large or small it is. Vector: Most image file types contain pixels.

Which SVG attributes are supported by React? ›

SVG is well-supported in modern browsers, including Firefox, Safari, Chrome, and Edge. All of these support embedding SVG directly in HTML, and React supports using SVG elements to build your components.

How to convert SVG to react native SVG? ›

STEP 1- first I used this link convert SVG to JSX for React to convert the SVG to JSX (Some times you don't need to convert it, it depends on icon itself). STEP 2- open new file component and import react and import { SvgXml } from 'react-native-svg' , then create a normal functional component inside.

How use Sprite SVG in React? ›

Here is how it's done: You give the <svg> element the class for your icon, and then make use of the <use> , give it the href attribute to the sprite, followed by an octothorpe (#) and then the name of the icon in the svg sprite.

Is SVG high resolution? ›

If you're working with high-quality digital logos and graphics, you might consider saving your files as PNG or SVG. Both are versatile formats with high resolutions, even at a large scale.

Is SVG better than CSS? ›

SVGs are easier to create, embed, and maintain. SVGs are accessible. SVG comes with set of accessibility elements that improve the accessibility of its content. You can learn more about them here.

Does SVG affect performance? ›

It won't be a problem for your website's performance, but it can negatively impact on your time and your server's bandwidth.

What is an Optimised file? ›

File Optimization is a form of lossy compression that permanently reduces the file size. This is key to its effectiveness and transparency, although can be perceived as a risk.

Do SVG images have resolution? ›

Advantages of SVG files.

Unlike raster files, which are made up of pixels, vector graphics like SVGs always maintain their resolution — no matter how large or small you make them. You don't have to worry about SVG images losing their quality in certain browsers or when you resize them to appear in different places.

Why SVG is not popular? ›

Because SVG is vector-based, it does not work well for images with lots of fine details and textures like photographs. SVG is best suited for logos, icons, and other “flat” graphics that use simpler colors and shapes. Also, while most modern browsers support SVG, older browsers may not work with them properly.

Is SVG infinitely scalable? ›

According to SitePoint, SVG uses shapes, numbers, and coordinates — rather than a pixel grid — to render graphics in the browser, which makes it resolution-independent and infinitely scalable. The power of SVG lies in the advantages it provides over its counterparts like JPG, PNG, and GIF.

Is SVG depend on resolution? ›

SVG does not depend on the resolution, which means it is resolution-independent. If we enlarge the image, it will not lose its shape.

Is SVG high or low quality? ›

SVG is ideal for high quality images and can be scaled to ANY size. Many people choose file formats based on file size restrictions - adding pictures to your website that will load as quickly as possible to improve SEO, for example.

Why is SVG so good? ›

SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not. SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images. Embedded SVGs can be styled using CSS.

What software to use for SVG files? ›

Inkscape. One of the most important tools for a graphics format is a decent drawing program. Inkscape offers state-of-the-art vector drawing, and it's open source. Moreover, it uses SVG as its native file format.

Can SVG have virus? ›

SVG files can also contain embedded JavaScript (JS) code, a potential vulnerability. For example, an infected SVG file can redirect users to a malicious website disguised as a reputable one. These sites often prompt users to install spyware disguised as a browser plugin or, ironically, a virus detection program.

Is SVG the best format? ›

SVG is the preferred format for images like user interface controls, logos, icon and vector-based illustrations. With SVG you can make three types of graphic objects: — Vectorial geometric elements like paths with their straight, curves and area between them.

Why is my SVG so blurry? ›

The issue of blurriness arises when you upload an image that has the exact pixel dimensions of the space you are targeting. The exact reason has to do with the resolution of modern screens.

Does SVG lose quality? ›

Scalability. One the major benefits of SVG is that they are resolution independent. This means that unlike file types such as JPG or PNG, SVGs retain the same quality no matter what screen resolution or size they are being at.

What is the advantages and disadvantages of a SVG file? ›

it's possible to view the contents of the SVG file in any browser (IE, Chrome, Opera, FireFox, Safari, etc.). Cons: – the file size is growing very fast, if the object consists of a large number of small elements; – it's impossible to read a part of the graphic object, only the entire object and it slows you down.

Is SVG as good as AI? ›

SVG files are scalable

AI files, on the other hand, don't offer the same level of scalability. The SVG file format was created to share high-quality 2D images on the internet. It is not only SEO friendly, but it's also scalable and easily editable.

What is the hardest thing to learn in React? ›

  • Mostly the syntax and how lifecycle hooks work.
  • Practice, practice, practice. Watching code-along videos, doing my own simple apps.
11 Oct 2020

Why is React so popular 2022? ›

Access to an extensive JavaScript Library: One of the major reasons for React's celebrity-like popularity is its library, which boasts millions of developers who can get help from diverse communities such as Stack Overflow, discussion forums (such as DEV's React community, Reddit's React community, etc.), React's ...

How do I download icons in React? ›

How to Install React Icons. To install the react-icons library, do the following: In your project folder, open the terminal of your code editor. Run the command npm install react-icons to install the library in your project folder.

Can you export SVGs from after effects? ›

Alternative way of exporting an SVG file from After Effects

After a series of trials and errors, we discovered the easiest way of exporting SVG files from After Effects. It requires the Bodymovin plugin and an online file converter.

How do I get the SVG element in React? ›

How to use SVG in React
  1. Use it as a regular image.
  2. Import it as a component via bundler magic (SVGR)
  3. Include it directly as JSX.
4 Nov 2021

How do I export a vector icon? ›

Once you have your icons in place, you can use the 'Export for Artboards' feature accessible under File > Export > Export for Screens. On the left side of the window select all or just few of the artboards you would like to export, and name them, as those names will be used for your output files.

Where can I get free SVG icons? ›

The free svg icons on Reshot are all sourced from real designers, individual contributors and brand partnerships.

Why is my react icons not working? ›

To solve the error "Module not found: Error: Can't resolve 'react-icons'", make sure to install the react-icons package by opening your terminal in your project's root directory and running the command npm install react-icons and restart your dev server.

Do SVGs load faster than images? ›

The implementation of Scalable Vector Graphics (SVG) in web design is fast. Raster images like JPEGs and PNGs typically have very large file sizes, slowing down websites as a visitor's browser tries to download all that information. SVGs, on the other hand, have much smaller file sizes and load much quicker.

Does Lottie export SVG? ›

If you preview the animation in the Lottie Previewer on web, then inspect the animation, you can copy the SVG code. Pasting that into a text file and saving it as a . svg file should give you a working SVG file.

Why is SVG icon not showing? ›

This problem is related to the fact that an SVG file (which inside has xml code) is linked from an external source (the CDN) and the browser blocks the svg sprite as a security measure. The most obvious solution is to find if there's any way to add a *. svg wildcard to exclude SVG files from being grabbed to the CDN.

How use sprite SVG in React? ›

Here is how it's done: You give the <svg> element the class for your icon, and then make use of the <use> , give it the href attribute to the sprite, followed by an octothorpe (#) and then the name of the icon in the svg sprite.

What is the fastest way to vectorize a logo? ›

So let's get started on turning an image into a vector.
  1. Step 1: Pick an Image to Convert to Vector. ...
  2. Step 2: Select an Image Trace Preset. ...
  3. Step 3: Vectorize the Image With Image Trace. ...
  4. Step 4: Fine-Tune Your Traced Image. ...
  5. Step 5: Ungroup Colors. ...
  6. Step 6: Edit Your Vector Image. ...
  7. Step 7: Save Your Image.

How do I Export a logo to SVG? ›

In Adobe Illustrator® this can be achieved using the “Save As” dialog:
  1. Double check that your image is vector-based ('. ...
  2. Open your file in Adobe Illustrator.
  3. Save your file by using the option “Save As”
  4. Once the dialog box is open, name the file and choose “SVG (svg)” from the dropdown “Format”
24 Jun 2021

Videos

1. Optimize SVG for React Applications with Illustrator | Part 2
(Code Tour)
2. ReactJS Convert SVG to React Component [ReactJS arabic]
(kimz codes)
3. How to Use SVG Icons in React with React Icons and Font Awesome
(Colby Fayock)
4. #5 Use SVG Icons In React | Google fonts and styles | Create layout component | PWA Tutorial
(Imran Sayed - Codeytek Academy)
5. Building the Ultimate React Icon Component
(Self Teach Me)
6. Node script to convert SVG files to React Components | Watch me code #reactjs
(Aravind Balla)
Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated: 12/14/2022

Views: 5587

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.