How to Use SVG Icons in React App?

June 21, 2022

2 min read

How to Use SVG Icons in React App?
Watch on YouTube

We don't need special treatment for SVG. We can have SVG tag in JSX the same way we have div or anchor tag.

export const CoffeeIcon = () => {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="1em"
      height="1em"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className="feather feather-coffee"
    >
      <path d="M18 8h1a4 4 0 0 1 0 8h-1"></path>
      <path d="M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4V8z"></path>
      <line x1="6" y1="1" x2="6" y2="4"></line>
      <line x1="10" y1="1" x2="10" y2="4"></line>
      <line x1="14" y1="1" x2="14" y2="4"></line>
    </svg>
  )
}

I store all the icons for my app in the ui/icons folder. If we open any of those files, we'll find a regular React component that I render as any other React component.

To find an SVG icon for my project, I usually go to websites like Google Fonts or Feather.

To get a bell icon, I would search for it, download the icon, then open it in the code editor.

Then I would create a component, copy-paste SVG content into the icon component, then fix all format errors with VS Code's auto-fix. We don't want a hardcoded size. Let's set it to 1em width and height to make it the same size as the parent. To inherit the parent's color, we'll set the stroke to currentColor.