Adding a badge within a SVG icon

Our UX Designer gave a SVG icon. Within the SVG icon, we want to add a badge.

At first glance, I was tinkering with the idea of absolutely positioning the badge within the SVG icon.

But there is a better alternative. SVG has a text element. It is possible to add a text element to the SVG icon provided by the designer. In this post, I will show you how.

SVG icon as React component

We can easily convert a SVG icon into a React component with a package named svgr.

There is an online utility where we paste a SVG element and get the resulting React component. The resulting React component after converting the SVG icon from the designer is shown below.

const CommentActive = props => (
    <svg viewBox="0 0 22 22" fill="currentColor" {...props}>
        <path
            d="M4 16h10.1l5.9 4V4c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2z"
            fillRule="evenodd"
            clipRule="evenodd"
        />
    </svg>
);

For our react component, we can pass additional props like width, height, color, etc.

Adding Badge to SVG component

We use the Text element. The size of the SVG icon viewBox is 22 by 22. To center the text, we add a text element at the center of the icon. If center does not suit us, we can adjust the position of the text element within the SVG view box.

import React from 'react';
import PropTypes from 'prop-types';

const CommentActive = props => (
    <svg viewBox="0 0 22 22" fill="currentColor" {...props}>
        <path
            d="M4 16h10.1l5.9 4V4c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2z"
            fillRule="evenodd"
            clipRule="evenodd"
        />
        <text x="11" y="12" textAnchor="middle" fontSize="8" fill="black">
            {props.count}
        </text>
    </svg>
);

CommentActive.propTypes = {
    count: PropTypes.number
};

export default CommentActive;

As you can see from the code above, the text element is at the center (11, 12). The text element uses the count prop to make it dynamic.

Using the above React component is very intuitive.

<CommentActive
  count={commentCount}
  width={24}
  height={24}
  className="btn-icon-selected"
/>

With this simple hack, we can easily add a badge within a SVG icon.

Related Posts

One thought on “Adding a badge within a SVG icon

Leave a Reply

Your email address will not be published.