How to optimize an SVG and include it in your React code
- UseΒ SVGOMGΒ to optimize the SVG
- When you take an SVG asset directly from Sketch, itβs horribly inefficient. You can paste the markup or import the file directly intoΒ SVGOMG, a free tool to that will typically shave off 40-60% of the file size, while also producing cleaner code. Toggle the markup/code view, copy the SVG output and proceed to step 2.
- Use SVGR to create a React component from SVG
- SVGR transforms SVG into ready to use components. It takes all of the annoying props like
fill-opacityand converts them to their JSX camel-case counterpartfillOpacityand close XML empty body tags. - NOTE: SVGR does add a return type. Also I prefer to write my functional component with arrow functions like so:
- SVGR transforms SVG into ready to use components. It takes all of the annoying props like
const MyIcon: React.FC = (
props: React.SVGProps<SVGSVGElement>
): React.ReactElement => (
<svg></svg>
);
- NOTE: When SVGR converts the SVG to a react component it will update the
idattribute values to the same generated values on each new SVG. So that the first id value will be assignedprefix__aand the second will be assignedprefix__band etc. Theseidsare then used in the CSSurl()functions (e.g.fill="url(#prefix__a)). Multiple, identicalidswill cause issues where an SVG will not properly render. First, applying the sameidto multiple elements is invalid HTML and should be avoided. Second, ids are used as a fragment identifier so when a CSS function likeurl()uses a fragment identifier it will return the firstidon the page. To circumvent this issue, we have to find and replace (command β shift β§ F) and update the ids with unique values. Remember to update theidvalues in theurl()function. I tend to prefix the ids with the name of the component so thatid="prefix__awill be replaced withid="my_icon_prefix__aand#prefix__awill be replaced with#my_icon_prefix__a.