How to turn an SVG into a React component
Updated
Pasting SVG markup into JSX almost works — but a handful of attribute names differ, and a component should let the app control its size and color. Here's what to change, and how to automate it.
What changes between SVG and JSX
- Hyphenated attributes become camelCase: stroke-width → strokeWidth, fill-rule → fillRule, stop-color → stopColor.
- class becomes className.
- Namespaced attributes lose the colon: xlink:href → xlinkHref, xml:space → xmlSpace.
- style="fill:red; opacity:.5" becomes style={{ fill: "red", opacity: ".5" }}.
- Every element must be closed: <path … /> rather than <path …>.
- data-* and aria-* attributes stay as they are.
A reusable icon component
Spread the component's props onto the <svg> so callers can set size, class, title and event handlers, and paint with currentColor so the icon follows the text color:
import type { SVGProps } from "react";
export function ArrowIcon(props: SVGProps<SVGSVGElement>) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={24} height={24} {...props}>
<path fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" d="M5 12h14M13 6l6 6-6 6" />
</svg>
);
}
// <ArrowIcon className="text-slate-500" width={16} height={16} />Automating it
For one or two icons, an online converter is quickest: paste the SVG, choose JSX or TSX, copy the component. For a whole icon library built into your app, a build step such as SVGR imports .svg files as components directly.
The Splice editor can also export any file — or a whole selection of files — as React components, alongside SVG and PNG.
When not to use a component
Large illustrations add their full markup to your JavaScript bundle as components. For big, static artwork an <img src="art.svg"> is lighter and cached separately; keep components for icons that need props, color or interaction.