How to Use SVGs as React Components with Webpack, Create React App, and Vite

A Comprehensive Guide to SVG Integration and Styling in React for Optimal Performance and Maintainability

Rakesh Kumar
Web Tech Journals
5 min readJul 4, 2024

--

How to Use SVGs as React Components with Webpack, Create React App, and Vite: A Comprehensive Guide to SVG Integration and Styling in React for Optimal Performance and Maintainability
How to Use SVGs as React Components with Webpack, Create React App, and Vite: A Comprehensive Guide to SVG Integration and Styling in React for Optimal Performance and Maintainability

Problem Statement: Traditional SVG Handling in Web Development

In traditional web development, handling SVG icons and graphics often involves importing them in CSS files or as standalone image files.

This approach can lead to suboptimal performance and maintainability challenges:

  • Suboptimal Performance: All SVGs are downloaded upfront, regardless of whether they are immediately needed, which can increase initial load times and impact user experience.
  • Maintenance Challenges: Managing and styling SVGs becomes cumbersome, especially in large applications with numerous icons and graphics scattered across different files.

Solution: Using SVGs as React Components

Solution: Using SVGs as React Components

By converting SVG icons into React components and integrating them seamlessly with tools like Webpack, Create React App, and Vite, developers can address these challenges effectively:

1. Setting up with Webpack

Step 1: Install the necessary packages:

npm install @svgr/webpack --save-dev

Step 2: Configure Webpack: Add the following rule to your Webpack configuration:

// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.svg$/,
use: ['@svgr/webpack'],
},
// other rules
],
},
// other configurations
};

Step 3: Import and Use SVGs:

import React from 'react';
import { ReactComponent as Logo } from './assets/logo.svg';

const App = () => (
<div>
<Logo style={{ width: '100px', height: '100px', fill: 'blue' }} />
</div>
);

export default App;

2. Setting up using Create React App

Create React App (CRA) includes SVGR by default, allowing you to import SVGs as React components without additional setup.

Step 1: Import and Use SVGs:

import React from 'react';
import { ReactComponent as Logo } from './assets/logo.svg';

const App = () => (
<div>
<Logo style={{ width: '100px', height: '100px', fill: 'blue' }} />
</div>
);

export default App;

3. Setting up using Vite for SVGs

Step 1: Create a Vite Project:

npm create vite@latest my-vite-app --template react
cd my-vite-app
npm install

Step 2: Install vite-plugin-svgr:

npm install vite-plugin-svgr --save-dev

Step 3: Configure Vite:

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr';

export default defineConfig({
plugins: [react(), svgr()],
});

Step 4: Import and Use SVGs:

import React from 'react';
import { ReactComponent as Logo } from './assets/logo.svg';

const App = () => (
<div>
<Logo style={{ width: '100px', height: '100px', fill: 'blue' }} />
</div>
);

export default App;

Styling SVG Components

You can style SVG components using several methods:

Option 1: Inline Styles:

<Logo style={{ width: '100px', height: '100px', fill: 'blue' }} />

Option 2: CSS Classes:

/* App.css */
.logo {
width: 100px;
height: 100px;
fill: blue;
}
import './App.css';
<Logo className="logo" />

Option 3: Styled-Components:

import styled from 'styled-components';
import { ReactComponent as Logo } from './assets/logo.svg';

const StyledLogo = styled(Logo)`
width: 100px;
height: 100px;
fill: blue;
`;

Option 4: Targeting SVG Elements:

.logo {
width: 100px;
height: 100px;
}
.logo .cls-1 {
fill: blue;
}
<Logo className="logo" />

Benefits of Using SVGs as React Components

1. Performance:

  • Scalability: SVGs scale without losing quality, ensuring sharp visuals on all devices.
  • Reduced HTTP Requests: Direct imports reduce the need for additional HTTP requests.
  • Efficient Rendering: React’s virtual DOM efficiently handles updates, enhancing performance.

2. Maintainability:

  • Componentization: SVGs as React components align with React’s component-based architecture, promoting reusability and modularity.
  • Consistent Styling: SVG components can be styled using CSS, inline styles, or CSS-in-JS libraries, ensuring consistent styling across your application.
  • Easy Prop Management: Props can dynamically alter SVG properties, making icons flexible and reusable.

3. Development Experience:

  • Type Safety with TypeScript: Type-checking ensures correct prop usage, reducing runtime errors.
  • Integration with Build Tools: Tools like @svgr/webpack and vite-plugin-svgr streamline SVG handling and optimization.
  • Easier Debugging: SVG components are part of the React component tree, making debugging simpler.

4. Design and UX:

  • Interactive SVGs: Event handlers can make SVGs interactive, enhancing user experience.
  • Animation: SVGs can be animated using CSS or JavaScript, creating engaging interfaces.

5. Accessibility:

  • Improved Accessibility: Accessibility attributes can be added to SVG components, making them accessible to screen readers and other assistive technologies.

6. File Size and Optimization:

  • File Size: SVGs are generally smaller than raster images, reducing the application bundle size.
  • Optimization: Tools like SVGO optimize SVG files during the build process, ensuring efficient loading.

Recap and Takeaways

Recap and Takeaways
  1. Optimized Performance: SVGs as React components are loaded on demand, reducing initial load times.
  2. Enhanced Maintainability: Aligns with React’s architecture, promoting reusability and modularity.
  3. Flexible Styling and Interaction: Styled and made interactive using CSS, inline styles, or CSS-in-JS libraries.
  4. Streamlined Development: Tools like Webpack, Create React App, and Vite, with plugins like @svgr/webpack and vite-plugin-svgr, facilitate seamless integration.

Conclusion

Handling SVG icons traditionally by importing them into CSS files can lead to performance and maintenance challenges.

Downloading all SVGs upfront increases initial load times, and managing them separately becomes cumbersome.

Converting SVG icons into React components offers a more efficient and maintainable solution.

This guide covers how to set up and use SVGs as React components with Webpack, Create React App, and Vite, detailing configuration, styling, and performance benefits.

Thank you so much for taking the time to read my article all the way through!

If you found it helpful or interesting, why not give it a round of applause by clicking those clap buttons?

Empowering web enthusiasts one bye at a time, simplifying the digital journey for all. By https://rakeshkumar-42819.medium.com

And hey, don’t miss out on more insightful content — hit that follow button to stay updated!

Get email alerts for my latest Medium posts! Click here.

Let’s learn and grow together. Happy Coding! 👏

--

--

Rakesh Kumar
Web Tech Journals

Skilled in frontend and backend development, I create robust solutions following best practices, ensuring compliance, and considering future perspectives.