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-opacity
and converts them to their JSX camel-case counterpart fillOpacity
and 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:
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
id
attribute values to the same generated values on each new SVG. So that the first id value will be assigned prefix__a
and the second will be assigned prefix__b
and etc. These ids
are then used in the CSS url()
functions (e.g. fill="url(#prefix__a)
). Multiple, identical ids
will cause issues where an SVG will not properly render. First, applying the same id
to multiple elements is invalid HTML and should be avoided. Second, ids are used as a fragment identifier so when a CSS function like url()
uses a fragment identifier it will return the first id
on 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 the id
values in the url()
function. I tend to prefix the ids with the name of the component so that id="prefix__a
will be replaced with id="my_icon_prefix__a
and #prefix__a
will be replaced with #my_icon_prefix__a
.