Integrating Custom SVG Icons into React Applications
Environment
Product Version | 10.0.0 |
Product | Progress® KendoReact SVGIcon |
Description
Integrating custom SVG icons into a React application involves using the SvgIcon component. The process generally requires creating an SvgIcon object and inserting the SVG path directly. This knowledge base article answers the following questions:
- How can I import SVG files directly into my React project?
- What is the best method to convert SVG files into SvgIcon objects in React?
Solution
To integrate custom SVG icons into your React application more efficiently, consider importing SVG files as strings. This approach allows you to dynamically convert SVG files into SvgIcon components without manually extracting paths or creating objects for each icon. Depending on your build system, you can utilize specific features or loaders to import SVG content directly. Here are two methods to achieve this:
Importing SVG as a String
-
Using Vite or Webpack: If your project uses Vite, you can import SVG files as strings using the
?raw
import feature. For Webpack, employ theraw-loader
to achieve a similar outcome.-
Vite example:
jsimport myIconSVG from './path-to-your/my-icon.svg?raw';
-
Webpack example:
jsimport myIconSVG from 'raw-loader!./path-to-your/my-icon.svg';
-
-
After importing the SVG as a string, you can directly use it to set the content of an SvgIcon object:
jsxconst myIcon = { name: 'myIcon', content: myIconSVG, viewBox: '0 0 24 24' };
-
After creating an SvgIcon object you are ready to use it:
jsx<Button svgIcon={myIcon}></Button>