In this article I’ll be exploring one approach to working with SVG and React. SVG has great tooling( Figma, Sketch, Illustrator) and has been around for a long time so there’s pretty good documentation about its features and quirks.

SVG and React

React supports using SVG tags inside JSX. This is no different than using other DOM elements like div o span. You can write SVG inside JSX but remember the rules of JSX. You have to make modifications like changing class to className . Because of this, you won't be able to directly paste the contents of an existing SVG file into JSX.

Common SVG Workflow and its problems

The SVG author starts working on the SVG asset using an editor like Sketch and will eventually export the SVG file so the developer can integrate it with the React code. The React developer will take the SVG file and convert it to JSX. With the JSX updated the developer can modify the SVG elements based on props or state. However, things get messy if the artist wants to keep working on the SVG file but the developer has already manipulated the SVG elements inside the JSX code ( a common escenario when the SVG needs to reflect the component state or props ). It would be convenient to keep things separated.

Libraries like svgr will generate a react component from an SVG file. This is useful in some situations because we can quickly re-generate a component when the SVG is updated. However this won’t be useful if we need to declaratively update our elements based on prop or state as we would lose the jsx modifications.

I’ve been thinking about improving the workflow when working with SVG files and the approach I’ll present is based on the following ideas:

I want to quickly prototype even if the final art is not ready, I should be able to work with a temporal SVG file that I create and later replace it with the final version, without losing the element declarative updates.

The SVG updates should live independent of the SVG code. I should be able to keep working on the SVG without losing the updates created in the React component.

It would be cool if I can load remote SVG files (that I trust) and update them from react using the declarative model that we love from React.

Enter react-svgmt (SVG Manipulation Tools for React)

My approach to solving those issues is the react-svgmt library. I’ll proceed to explain why I think is a good approach to handle SVG loading and manipulation and a good alternative to create SVG based components and applications.

Loading a SVG file with react-svgmt

Let’s start by loading a SVG file from Github and doing some modifications to it.