SVG Optimization
This document provides guidelines on how to efficiently use Scalable Vector Graphics (SVGs) in the
frontend React application. SVGs are an essential part of modern web development, offering
scalability, flexibility, and customization options. In our project, we store all SVGs in the
public folder, optimize them using “Optimize SVG” tools, and leverage CSS modules for styling.
Storing SVGs in the public Folder
In our project, all SVG assets should be placed in the public folder. This folder is the
recommended location for static assets that are not part of the application bundle. Placing SVGs in
the public folder ensures that they are accessible directly without being bundled by the build
process.
-
Create a
publicFolder: If it doesn’t already exist, create apublicfolder at the root of your project. -
Organize SVGs: Place your SVG files inside the
publicfolder. You can organize them into subdirectories based on your project’s needs.
public/ ├── modules/ │ ├── svg1.svg │ ├── svg2.svg │ └── ... └── ...Optimizing SVGs
Optimizing SVGs is essential to reduce their file size and improve loading performance. To optimize SVGs, we recommend using an online tool like SVG Viewer or other similar tools.
Follow these steps to optimize your SVGs:
-
Access the SVG Viewer Tool: Visit SVG Viewer in your web browser.
-
Upload SVG: Use the tool to upload your SVG file(s).
-
Optimize: Use the optimization options provided by the tool to optimize your SVGs. Typically, this includes removing unnecessary metadata, cleaning up the SVG code, and reducing unnecessary details.
-
Replace the original SVG: After optimization, replace the existing svg with the optimized(minified) version
Optimizing SVGs using these steps will help reduce the file size and improve the loading performance of your SVG assets in the application
Styling SVGs with CSS Modules
To style SVGs efficiently and maintainably, you can use CSS Modules. CSS Modules allow you to scope CSS styles to specific components or elements, which is particularly useful when working with SVGs.
Here’s how you can use CSS Modules to style SVGs:
-
Create a CSS Module: Create a CSS Module file (e.g.,
styles.module.css) alongside your React component file. -
Import the CSS Module: Import the CSS Module into your React component.
Apply Styles: Apply styles to your SVG elements using the CSS Module classes.
import classes from './styles.module.css'
return <svg className={classes.icon}>{/* SVG content */}</svg>Define Styles in the CSS Module: Define your styles in the CSS Module file. These styles will be scoped to the component, preventing unintended style conflicts.
.icon > path,.icon > g > path { fill: var(--theme-blue); /* Example styling */}