Flexible SVG components in React

Getting SVGs into our projects

Using SVGs on the web isn’t hard, the format is supported by all major browsers since IE9. Of course, there are multiple ways to include them into our projects, like using them in image tags, as background-images or directly inline.

Preview of the SVG file.
<svg 
version=”1"
xmlns=”http://www.w3.org/2000/svg"
viewBox=”0 0 50 50"
>
<path
fill=”#FFF”
d=”M33.5 45.5c-.1 0-.2 0-.3-.1L25 41.3l-8.2 4.2c-.1 0-.2.1-.3.1-.1 0-.2 0-.3-.1-.2-.1-.3-.3-.3-.5v-5.3c0-.2.1-.3.2-.4l4.1–4.4v-4.2L5 35.1h-.2c-.1 0-.3 0-.4-.1-.2-.1-.3-.3-.3-.5v-5.2c0-.2.1-.4.3-.5L20 17.7V9.5c0–3.1 2.2–5.6 4.9–5.6s4.9 2.5 4.9 5.6v8.1l15.6 11.1c.2.1.3.3.3.5v5.2c0 .2-.1.4-.3.5-.1.1-.2.1-.4.1h-.2l-15.1–4.5v4.2l4.1 4.4c.1.1.2.3.2.4v5.3c0 .2-.1.4-.3.5 0 .2-.1.2-.2.2zM25 38c.1 0 .2 0 .3.1l5.9 3v-.6l-4.1–4.4c-.1-.1-.2-.3-.2-.4v-8.3c0-.2.1-.4.3-.5.1-.1.2-.1.4-.1h.2l15.1 4.5v-.9L27.2 19.3c-.2-.1-.3-.3-.3-.5V9.5c0–1.4-.9–2.6–1.9–2.6s-1.9 1.2–1.9 2.6v9.3c0 .2-.1.4-.3.5L7.2 30.4v.9l15.1–4.5h.2c.1 0 .3 0 .4.1.2.1.3.3.3.5v8.3c0 .2-.1.3-.2.4l-4.1 4.4v.6l5.9–3s.1-.1.2-.1z”
/>
</svg>
<svg ... fill="#f00">
<svg ... fill="#f00">
<path
fill=”fill”
d=”M33.5 ...”
/>
</svg>
//the d property was shortened for readability purposes

Lord of the Props

This is a perfect opportunity for controlling these properties via props thrown into a React component that renders the svg tag. We can now easily define our Airport stateless functional component as

const Airport = props => (
<svg version={1} viewBox="0 0 50 50" {...props}>
<path
fill="fill"
d="M33.5 ..."
/>
</svg>
);
//the d property was shortened for readability purposes
<Airport width={20} height={20} fill='#fff' />

SVGR to the rescue

There surely must be a package that handles all this — and SVGR is the one. After installing the dependency via npm install svgr in our project root, we can easily create React components off our many .svg files automatically.

"icons": "svgr --replace-attr-value '#FFF=fill' -d ./src/icons/js ./src/icons/svg"
A slick looking React component

Taking this further

We might want to access the icons by a String value, or we might want to color multiple path inside our components differently, which is all possible. To keep this post concise, I will cover these aspects in the future. Stay tuned!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store