How to Load SVG with React and Webpack (2024)

Introduction

As developers, we want all our images to look sharp and nice, even when we scale them up. To achieve the level of sharpness we want for our websites using bitmap images, such as JPEGs, GIFs, and PNGs, we have to increase file size, which greatly impacts the performance of the website. Vector images, however, looks crisp regardless of screen resolution and are relatively small in size.

In this guide, we'll learn about Scalable Vector Graphics (SVG) and explore the standard way of importing SVG in a React Application bundled with Webpack.

What is SVG?

SVG is an XML-based markup language for describing two-dimensional-based vector graphics. SVG is essentially to graphics what HTML is to text.

SVG images basically take the place of traditional images in other formats like JPEG, PNG, TIFF or GIF.

Advantages of using SVG over other image formats are:

  • SVG images can be searched, indexed, scripted, and compressed
  • SVG images are scalable
  • SVG can be created and edited with any text editor
  • SVG images do NOT lose quality even if they are resized or zoomed
  • SVG images can be animated, unlike other traditional image formats

Let's take a closer look at how to use SVG images. The xml code below creates a rectangle:

rectangle.svg

 <svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="green" /></svg> 

The most basic way to embed an SVG via an <img> element is to reference it in the src attribute, as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio).

 <img src="rectangle.svg" alt="A Rectangle Image with SVG" height="45px" width="45px" /> 

The easiest way of implementing an SVG in a React app is as follows:

 const App = () => <img src="/images/rectangle.svg" alt="A Rectangle Image with SVG" />; 

However, in most cases, SVGs are usually pretty small, and in these cases we are better off inlining the images as data URLs, limiting the amount of requests a browser has to make to the server in order to render the webpage.

To transform an SVG image into a Data URL, we will need an appropriate webpack loader in our bundler. The most common webpack loader for this is svg-url-loader, which can be added as shown below:

 npm i svg-url-loader --save-dev 

Add to webpack.config.js:

 const webpack = require('webpack');module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: [ { loader: 'svg-url-loader', options: { limit: 10000, }, }, ], }, ], }, ...}; 

Import the file into your React app:

 import rectangle from 'images/rectangle.svg';const App = () => <img src={rectangle} alt="" />; 

The output in the DOM will be something like this:

 <img src="ebbc8779488b4073081931bd519478e8.svg" alt="" /> 

You can check out svg-url-loader for more on the configurations.

In the examples above, the svg-url-loader can only be used in the traditional way, including images in a web application such as background-image or content. The next question is how to use an SVG image as a React Component.

SVG as a React Component

The solution is not farfetched. We'll need the help of another awesome webpack loader called svgr, which, according to the website, transforms the SVG into a ready-to-use React component.

So how do we use this awesome tool? Lets start by updating our webpack.config.js:

 const webpack = require('webpack');module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: ['@svgr/webpack'], }, ], }, ...}; 

Then we can install it as a dev-dependency in the usual way:

 npm install @svgr/webpack --save-dev 

Once you start your application, Webpack will do its thing and you don't need to worry about your SVGs anymore. You can put your SVG files anywhere in your src/ folder and import them wherever you need them as React components.

Lastly, import the file in your React app:

 import Image from 'path/image.svg';const App = () => ( <div> <Image /> </div>) 

This method is generally referred to as inline-svg.

A lightweight alternative solution to svgr is react-svg-loader.

 const webpack = require('webpack');module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { loader: 'react-svg-loader', options: { jsx: true // true outputs JSX tags } } ], }, ...}; 

And install as usual:

 npm install react-svg-loader --save-dev 

For the most part, we do not want all our SVG files to be loaded as a React components. We could combine the above methods depending on the use case. All we have to do is update our webpack configuration.

The example below uses svgr and url-loader, a webpack loader which transforms files into base64 URIs.

 const webpack = require('webpack');module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: ['@svgr/webpack', 'url-loader'], }, ], }, ...}; 

The usage in your application would look this:

 import imageUrl { ReactComponent as Image } from 'path/image.svg';const App = () => ( <div> <img src={imageUrl} alt="" /> <Image /> </div>) 

Conclusion

This guide has provided you with a quick intro into how to import SVG into your React Application using webpack as the bundler.

Here are a few other resources on SVG and its numerous applications:

How to Load SVG with React and Webpack (2024)

FAQs

How do I load SVG in React component? ›

Using an SVG as a component

A sample use case would look like this: import { ReactComponent as Logo} from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <Logo /> </div> ); } export default App; Although this approach is simple to implement, it has some difficulties.

How to make SVG 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. The viewBox attribute specifies the aspect ratio and coordinate system of the SVG, allowing it to scale correctly.

How to import SVG from public folder in React? ›

Importing SVG into React Next JS

In the above code, we are importing an SVG file named 'logo. svg' from the 'public' directory. We are then using the 'Image' component from 'next/image' to render the SVG. The 'Image' component automatically optimizes the SVG for better performance.

Why use vite over webpack? ›

Vite emerges as the clear winner in bundling speed, drastically reducing build times. While Webpack offers configurability and robust development tools, it lags behind Vite. These figures are based on a medium-sized Vue. js application with a moderate number of dependencies.

How to use SVG as background image in React? ›

SVG component code: import React from "react"; const testSVG = props => { return ( <svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 193.3 129.7"> <g> <g> <g> <path fill="#434343" class="st0" d="M162.

How to convert SVG file to React component? ›

Using SVGR in the command line

Then, we call SVGR in the command-line, passing in the . svg file and other flags to replace different attributes with our own values. The above command will take our logo. svg file and convert it to a React component.

How do you deal with SVG in 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.

How do I create a dynamic SVG in React? ›

Method 1: Using template literals and data-URI

Copy the SVG contents within a JavaScript template literal `...` and replace the text you want to change dynamically. In the following example to: ${amount}&#8467; Convert the string into a data-uri with "data:image/svg+xml;base64," + btoa(source) and use it as image URL.

How to increase the size of a SVG image 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. Note: To change the color you can use . componentClass path { fill: "color" } , but if you change the scale on .

How to do dynamic import in React? ›

The React. lazy() function allows you to render a dynamic import as a regular component. Basically, React. lazy() makes a call to a dynamic import and returns a promise.

How do I use custom SVG icons in 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.

Top Articles
Transfer apple account balance to Apple C…
How do you learn and master bitcoin script encoding and what are the best resources and tools?
Chs.mywork
Foxy Roxxie Coomer
St Als Elm Clinic
Ogeechee Tech Blackboard
Mycarolinas Login
ATV Blue Book - Values & Used Prices
Craigslist Alabama Montgomery
Evil Dead Rise Showtimes Near Regal Columbiana Grande
What is Cyber Big Game Hunting? - CrowdStrike
Dit is hoe de 130 nieuwe dubbele -deckers -treinen voor het land eruit zien
Sport-News heute – Schweiz & International | aktuell im Ticker
Billionaire Ken Griffin Doesn’t Like His Portrayal In GameStop Movie ‘Dumb Money,’ So He’s Throwing A Tantrum: Report
Transfer and Pay with Wells Fargo Online®
Rondom Ajax: ME grijpt in tijdens protest Ajax-fans bij hoofdbureau politie
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Xfinity Outage Map Fredericksburg Va
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
Bellin Patient Portal
Bidrl.com Visalia
What Is a Yurt Tent?
Pacman Video Guatemala
Lawrence Ks Police Scanner
Does Circle K Sell Elf Bars
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Justin Mckenzie Phillip Bryant
Marine Forecast Sandy Hook To Manasquan Inlet
Retire Early Wsbtv.com Free Book
Page 5662 – Christianity Today
Mckinley rugzak - Mode accessoires kopen? Ruime keuze
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
Wait List Texas Roadhouse
Bartow Qpublic
Weather Underground Cedar Rapids
Sand Castle Parents Guide
21 Alive Weather Team
Costco Gas Foster City
Mitchell Kronish Obituary
How Big Is 776 000 Acres On A Map
Noh Buddy
Ts In Baton Rouge
Aznchikz
Upcoming Live Online Auctions - Online Hunting Auctions
Mlb Hitting Streak Record Holder Crossword Clue
Brutus Bites Back Answer Key
How to Do a Photoshoot in BitLife - Playbite
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Nkey rollover - Hitta bästa priset på Prisjakt
32 Easy Recipes That Start with Frozen Berries
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 6436

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.