The Best Way to Import SVGs in React (2024)

The Best Way to Import SVGs in React (3)

Who doesn’t appreciate the coolness that SVG brings? SVG support in HTML 5 is by all means a great technology that offers a lot. And in all its simplest forms, we appreciate how our icons or graphics can scale without losing their sharpness. Also, we like to be able to control and play with the details that form our graphics, to style them, animate them, and so on.

In this article, I will show the two methods to import SVG assets into React components. I like to call them the in-source assets as they will be situated in our source (create-react-app by default doesn’t allow importing from outside src.That’s restricted unless you eject and change the config. (That’s for a good reason, which I’ll treat in another article.)

I will show two methods, the old one and a kind of new one that comes with create-react-app V2. I’ll explain the motivation and the why.

Note: If you’re in a hurry, scroll down to the next heading.

The Best Way to Import SVGs in React (4)

First of all, due to webpack and loaders url-loader and file-loader, importing images and SVG is possible. This was already leveraged by default from the start.

Note: url-loader creates a data URL from images (base-64 data URL, embedded in the HTML directly, for a fast load and no fetch after page load). That’s unless they are greater than a certain limit (in create-react-app, it’s 10,000), in which case it falls back to file-loader, which will output the imported file into the configured output. (This is the default behavior if no fallback is defined, and so it is with create-react-app). And the output in create-react-app is the build folder in production and the development server in development.

The code below is captured from create-react-app webpack.config.js:

url-loader

The Best Way to Import SVGs in React (5)

file-loader

The Best Way to Import SVGs in React (6)

output

The Best Way to Import SVGs in React (7)

This gives a good idea of how it happens. (If you want to know more, read about webpack loaders and system).

Now back to how we import. Let’s start with the old way. (Make sure to read to the end. If you’re in a hurry, jump to the next headline.)

I will take an example from an actual project. I needed to build a component to highlight or notify about connection and disconnection in a real-time application.

Back to the line. To import, we go with the following:

The Best Way to Import SVGs in React (8)
import myIcon from './relative/path/to/icon.svg'

We use the normal import syntax, and we import our SVG assets, thanks to the url-loader for webpack. Our variable will hold a URL to the SVG icon.

We use it like this:

The Best Way to Import SVGs in React (9)
<img src={myIcon} alt="icon" />

We come to the line with the problem, why this may not be ok or why we may need something else:

SVG as an image doesn’t offer any control. We will not be able to style it as we want and neither animate nor control the inner SVG components.

Here’s an image that illustrates the different ways to use SVG with HTML and how they compare in terms of features.

The Best Way to Import SVGs in React (10)

We can see that the inline method is the most suitable. So you might just think the way to go is to make components that will render our inline SVG. And that’s what the second method is about.

Due to the disability of the image method, an issue was raised. create-react-app v2 ended up including a solution for that, as it did with a bunch of other features. Our life was just made even easier. We need to thank all the great guys out there (thank you, folks). You can look at this thread to see when the issue was filled https://github.com/facebook/create-react-app/issues/1388.

This time a webpack config is leveraged for us, using the svgr loader for webpack, which you can check out here https://www.npmjs.com/package/@svgr/webpack).

Also, you can check out the svgr repo https://github.com/smooth-code/svgr to learn more about svgr.

There is a playground that you can check, too.

svgr takes an SVG file and transforms it into a React component that renders an inline SVG.

Here is create-react-app webpack config:

The Best Way to Import SVGs in React (11)

This is the story. Let’s see how we do the import.

Back to our example — let’s make some modifications.

The Best Way to Import SVGs in React (12)
import { ReactComponent as MyIcon } from "./icon.svg"

We can import both versions, which doesn’t really make sense, but anyway, let’s see it.

import myIconUrl, { ReactComponent as MyIcon } from "./icon.svg"

Make sure to import ReactComponent from the model as a specific component name so that it makes sense. And make sure you respect that it starts with a capital letter. Otherwise JSX will be transpiled to a string literal and not a variable.

Here the component in place:

The Best Way to Import SVGs in React (13)
<MyIcon />
<MyIcon className="someClassThatWillBeUsedInCSS" alt="icon" />

Now we need to see how both methods render.

I made a refactor to my ConnectionNotification component, which, by the way, I will share and publish once it’s all good to go. (It handles showing when it’s disconnected. At the start, it shows if it’s connected, or, if not, it will show “disconnected” but only after a wait time passes. Also “connected” will show immediately and hide after a timeout. In short it handles the notification feature, and well. And it can be costumed with style, and icons, text, etc.)

The Best Way to Import SVGs in React (14)

The component above renders to the following inline SVG, as you can see:

The Best Way to Import SVGs in React (15)
The Best Way to Import SVGs in React (16)

While the image version:

The Best Way to Import SVGs in React (17)

Will render:

The Best Way to Import SVGs in React (18)

Note that it makes no difference in my use case from a style viewpoint. However, know that inline SVG will load faster, which alone is a good reason. If I want, I can make some animations on the inner SVG components.

Now that you have an inline SVG, you can work as usual and have all the control that you need. By far this is the best way to go.

Note: Here a link for a gist that shows one of the SVG sprite files I used.

https://gist.github.com/MohamedLamineAllal/a1bcca5c4e7d12defddfceabc2a2734d?short_path=7802baa

And just to show it, here is my final connection component rendered:

The Best Way to Import SVGs in React (19)
The Best Way to Import SVGs in React (20)
The Best Way to Import SVGs in React (21)
The Best Way to Import SVGs in React (22)

I hope you love it.

The Best Way to Import SVGs in React (2024)

FAQs

What is the best way to add SVG to React? ›

We can use inline SVG directly in React components by including the SVG code as a distinct <svg> element. It involves embedding the SVG markup directly within the JSX code of a React component. In this example, we directly embed a sample SVG element into the App component.

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

If you're working with simple graphics, icons, or logos, SVG may be the better choice due to its smaller file sizes and ability to be scaled without losing quality. However, if you're dealing with complex images or photographs, a PNG may be more appropriate due to its lossless compression and support for transparency.

How to lazy load SVG in React? ›

Dynamic Import of SVG as a React Component

In the above code, we are using the 'React. lazy' function to import an SVG file named 'logo. svg' as a React component named 'Logo'. The SVG is then rendered inside a 'Suspense' component, which displays a fallback UI while the SVG is loading.

How to make SVG responsive in React? ›

Making SVG Images Responsive in React

In React, you can make an SVG image responsive by controlling its width and height using CSS. To make an SVG image responsive, you first need to ensure that the SVG has a viewBox attribute.

What is the best way to insert SVG? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

Can we make SVG responsive? ›

This adjustment can be made directly within the SVG's code. And there you have it! We've successfully created a responsive SVG that adjusts its size while always keeping the swirl loop at the bottom, ensuring it doesn't get distorted.

Do SVGs load faster than PNGs? ›

SVG files are also usually smaller, which makes them quicker to load on a page.

What are 2 disadvantages of SVG files? ›

Disadvantages of SVG files.

SVG files are great for web graphics like logos, illustrations, and charts. But their lack of pixels makes displaying high-quality digital photos difficult. JPEG files are generally better for detailed photographs. Only modern browsers can support SVG images.

What is the best image type for react? ›

Prefer PNG over SVG for react-native mobile apps because its rendering is less CPU intensive, and comparing to web apps user don't need to load all images on each app launch but only on installation, so the size doesn't matter that much.

How can I make SVG files load faster? ›

How to Speed Up SVG Loading
  1. To speed up SVG loading, one effective technique is minification. ...
  2. Using the viewBox attribute is another way to improve SVG loading time. ...
  3. Additionally, leveraging CSS styling is recommended as a way to optimize SVGs. ...
  4. Yes, SVG files can be resized without losing quality.

How to optimize SVG? ›

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.

How do I reduce SVG size in React? ›

How to reduce svg file size in React?
  1. Installed vite image optimizer plugin. But it didn't work on images greater than 5mb.
  2. I tried to load svg components lazily using "lazy" and "suspense". These reduces the page size of in which svg is imported as react component.
Jan 21, 2024

How to import SVGs in React? ›

SVGs can be imported and used directly as React components in your React code. The image is not loaded as a separate file; rather, it's rendered along with the HTML. A sample use case would look like this: import { ReactComponent as Logo} from './logo.

How do I load animated SVG in React? ›

I.) React websites based on Create React App
  1. Step 1.) Add SVG: Add the exported SVG into your project - stopwatch. ...
  2. Step 2.) Create Custom Component: Add your wrapper component ( Stopwatch.jsx in this example) with the structure below: ...
  3. Step 3.) Move Javascript Code: ...
  4. Step 4.) Handle Style Tags:
Mar 2, 2023

How to use SVG as React component in next js? ›

Simply import the SVG file and use it like any other React component: import MySvgIcon from '../path/to/MySvgIcon. svg'; const MyComponent = () => { return ( <div> <MySvgIcon /> {/* Other JSX */} </div> ); };

How do I add SVG animation to React? ›

I.) React websites based on Create React App
  1. Step 1.) Add SVG: Add the exported SVG into your project - stopwatch. ...
  2. Step 2.) Create Custom Component: Add your wrapper component ( Stopwatch.jsx in this example) with the structure below: ...
  3. Step 3.) Move Javascript Code: ...
  4. Step 4.) Handle Style Tags:
Mar 2, 2023

How do I use SVG in React next? ›

Simply import the SVG file and use it like any other React component: import MySvgIcon from '../path/to/MySvgIcon. svg'; const MyComponent = () => { return ( <div> <MySvgIcon /> {/* Other JSX */} </div> ); };

How to pass color to SVG React? ›

We can only change the color of the SVG using the fill attribute of the <img> tag. return <img src={CircleSvg} alt="My SVG" fill="red" />; }; Here, we are using the fill attribute of the <img> tag to change the color of the SVG.

How do I add SVG to React tailwind? ›

Here are the steps to take to convert your AcmeLogo.svg file to a React component:
  1. Run npm install -g svg-to-react-cli in your terminal.
  2. Run svgtoreact <PATH_TO_SVG> <PATH_TO_EXPORT_REACT COMPONENT> like so: svgtoreact /path/to/AcmeLogo. svg /path/to/AcmeLogo. js.
Jun 13, 2021

Top Articles
Obesity Hypoventilation Syndrome
How is CSR related to sustainability? - Turnkey
Where To Go After Howling Pit Code Vein
Tattoo Shops Lansing Il
Hannaford Weekly Flyer Manchester Nh
Chicago Neighborhoods: Lincoln Square & Ravenswood - Chicago Moms
Mrh Forum
Jeremy Corbell Twitter
Cumberland Maryland Craigslist
Craigslist Vermillion South Dakota
Chuckwagon racing 101: why it's OK to ask what a wheeler is | CBC News
Embassy Suites Wisconsin Dells
Costco in Hawthorne (14501 Hindry Ave)
Xm Tennis Channel
The Rise of Breckie Hill: How She Became a Social Media Star | Entertainment
Discover Westchester's Top Towns — And What Makes Them So Unique
People Portal Loma Linda
Samsung Galaxy S24 Ultra Negru dual-sim, 256 GB, 12 GB RAM - Telefon mobil la pret avantajos - Abonament - In rate | Digi Romania S.A.
Conan Exiles Colored Crystal
Ms Rabbit 305
Vegito Clothes Xenoverse 2
Stihl Dealer Albuquerque
Https E22 Ultipro Com Login Aspx
Discord Nuker Bot Invite
Nk 1399
They Cloned Tyrone Showtimes Near Showbiz Cinemas - Kingwood
Ihs Hockey Systems
Halsted Bus Tracker
Hoofdletters voor God in de NBV21 - Bijbelblog
6465319333
Everstart Jump Starter Manual Pdf
Babbychula
Makemkv Key April 2023
SOC 100 ONL Syllabus
Priscilla 2023 Showtimes Near Consolidated Theatres Ward With Titan Luxe
Craigslist Jobs Brownsville Tx
Cdcs Rochester
Final Jeopardy July 25 2023
Thelemagick Library - The New Comment to Liber AL vel Legis
Gold Dipping Vat Terraria
Nba Props Covers
Gfs Ordering Online
Lbl A-Z
Trivago Anaheim California
Divinity: Original Sin II - How to Use the Conjurer Class
Celsius Claims Agent
Enr 2100
Go Nutrients Intestinal Edge Reviews
House For Sale On Trulia
Food and Water Safety During Power Outages and Floods
Swissport Timecard
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated:

Views: 6454

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.