Changing SVG image to React component

React+javascript, React+typescript

Duvvuru Kishore
2 min readJul 30, 2023

In React projects its always better to change plain SVG image to React component for following reasons

  1. If you have complex SVGs with many elements and attributes, the JSX syntax for rendering SVG in React can become harder to maintain.
  2. Next if want to use same SVG across different components , we can create a simple SVG folder and file .Separate SVG into separate components so that it makes easier to reuse and maintain consistency.
  3. Using large and complex SVGs directly in React can impact the initial load time and performance of your application

Its time to change SVG images into React components

SVG:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Layer_1" focusable="false" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
<style type="text/css">
.st0{fill:#747474;}
</style>
<path class="st0" d="M256,8C119,8,8,119,8,256s111,248,248,248s248-111,248-248S393,8,256,8z M256,456c-110.5,0-200-89.5-200-200
S145.5,56,256,56s200,89.5,200,200S366.5,456,256,456z"/>
</svg>

SVG TO REACT COMPONENTS:

import React from 'react';

const CheckRegular = () => {
return (
<svg
version="1.1"
id="Layer_1"
focusable="false"
width="21"
height="21"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
>
<path
fill="#747474"
d="M256,8C119,8,8,119,8,256s111,248,248,248s248-111,248-248S393,8,256,8z M256,456c-110.5,0-200-89.5-200-200
S145.5,56,256,56s200,89.5,200,200S366.5,456,256,456z"
/>
</svg>
);
};

export default React.memo(CheckRegular);

While changes to react components there will be errors for some in SVG code, just deleting those will not impact anything. Most importantly path in main element to show appropriate image.

Why we used React.memo for SVG image

In React, it is often desirable to prevent unnecessary re-renders of that component when the parent component re-renders. This is because SVG components can have complex structures and calculations, and re-rendering them unnecessarily can impact performance.

Next time when you are using SVG , change them into React components.

--

--