Scalable Vector Graphics, or SVGs, are a powerful secret weapon in the landscape of digital media.
Unlike raster images, which are grids of pixels that blur when enlarged, SVGs are vector images that can be infinitely scaled upward with no loss of quality. Additionally, as an XML-based image format, SVGs boast a lightweight digital footprint, making them load faster and take up less space than their graphical counterparts.
SVGs are additionally quite versatile. They can used for:
- crisp and animated favicons in the browser
- unique, bespoke text effects
- blurred placeholders for lazy-loaded images
- dynamic data visualization
- 3D graphics
When it comes to React.js applications, there are several approaches one can take when incorporating SVGs into one's project. Here are the core methods for integrating SVGs into your React project:
- Deploying them as regular images, similar to JPEGs and PNGs
- Use bundlers to import the SVGs as components, thanks to tools like SVGR
- Write the SVGs as JSX, React's own XML extension
We'll now break down each method, offering the pros and cons to the usage of each in your project.
SVGs can be used as an image, so we'd treat them as any other image resource:
Pros:
- Simple
- No learning curve
Cons:
- SVG can't be customized
Use case: Importing an SVG as an image file is a simple replacement for raster images that don’t need customization, e.g., logos.
When importing an SVG as a component, we can inline SVGs directly in our markup & use them as a component.
is the library that powers this ability. While setting this up can be a little hairy, many popular frameworks (Create React App, Gatsby) support this feature out of the box.
Pros:
- Easy to handle a large amount of SVG
- Powerful templating
Cons:
- May need additional configuration
- Writing React component template is not straightforward
Use case: A good example of using bundler magic with your SVGs is if you wanted to build a custom SVG icon library for a brand. You can use the templating to programmatically generate a variety of icons, saving yourself a ton of time after some initial investment in the config.
As an XML-based syntax in its own right, JSX supports all SVG tags. We can (almost) paste the SVG directly into our React components!
This is the most straightforward method to take full advantage of SVG without bundler support, which is why we will use this method for all of our examples later in this article.
The only gotcha is that instead of regular HTML attributes, we have to use JS property syntax, e.g stroke-width
-> strokeWidth
Pros:
- Straightforward
- Minimal changes required to convert the SVG XML into valid JSX
Cons:
- Depending on the SVG, component code may not be readable
- Not scalable for a large number of SVGs
Use case: Writing SVGs as JSX and using them as components in your application is a good way to create one-off graphics such as illustrations, or blog headers.
This article will not be complete if we don’t at least show off a few SVG techniques. In the following examples, we will share with you some tips and tricks for making the most of this powerful graphical medium.
All examples will use (CRA) and CSS Module. A way to start a CRA project is using . Otherwise, make sure (any TLS versions will do) and run this:
npx create-react-app my-app && cd my-app
Here's what we'll be making:
Let’s try writing this SVG from scratch. All we need is one circle, so this is the SVG in its entirety:
Now let's make it move! We can now attach class names to SVG elements and animate them with CSS transform & animation.
Animating paths is a classic SVG trick, and the secret to it is using stroke-dasharray
. This property creates dashed lines, like in the image below:
That's nothing too exciting. However, things get more interesting when you realize that these dashes can be offset. What if, instead of many short dashes, we have a single dash whose length is the same as the circle's circumference? We can then move that dash around by changing the offset, giving the appearance that the path is being shortened or lengthened.
Let's give it a try:
Setting stroke-dashoffset
to a negative value pushes the path further down & create the looping effect.
Finally, to make the animation more dynamic, let's also rotate the circle.
prefers-reduced-motion
Loading icons typically don't have the type of animations that could cause issues. However, for a larger graphic with lots of animation, writing gentler animation code is a good practice. In our case, we can extract the animation duration into a CSS variable & define a larger value inside of the prefers-reduced-motion
media tag.
Customize with React
Now let's make the icon customizable. We want to allow users to change color & thickness.
If color is unset, the stroke color will inherit from its parent.
Accessibility
Since our loading icon does not contain any text, we should give it a <title> so a screen reader can make sense of it. To dive deeper into accessibility with SVGs, cover this topic extensively.
Now that we have a title, a tooltip will show up when the cursor hovers over the SVG. If that seems unnecessary, we can get rid of it by adding pointer-events: none
to SVG's style.
Result
And with that, we can now use this loading icon anywhere! This contains a slightly more complex version of the icon above. This lightweight example can be easily saved and imported into any of your projects.
SVG can do amazing things with text, but let’s start with something simple. Like the previous example, we will start with just the SVG and then work our way up to incorporating React.
The graphic we'll be working with is rather long, but here's the main parts:
SEO Concerns
We can nest this SVG inside heading tags. It is valid HTML (test it ) and screen readers can pick up the text inside.
SVG assets
Let's look at the parts. <defs>
is SVG's compartment where we can put stuff for later use. That can be shapes, paths, filters, and gradients, such as in the SVG above. True to the compartment analogy, browsers will not render elements placed inside a <def>
block.
If we want to apply the defined gradient to the text object, we can reference its id
with the following syntax:
Sweet! But we can achieve this effect in . So let's see what else SVG can do.
Creating outline text is relatively easy with SVG: just change fill
to stroke,
and the gradient will still be applied.
And better yet, that gradient can be animated.
The syntax for creating SVG gradient animation is quite verbose, unfortunately.
Let's make something even cooler. How about this XRay hover effect?
The trick here is to use text as a clipping path. We can then animate a circle clipped inside the text as we move the cursor in React.
We'll create a new element called clip-path
(clipPath
in JSX) in <defs>
, and place <text>
into it. This serves two purposes: so we can (1) use the text as a mask and (2) clone it to create the outline effect by using <use>
.
So far, we've been using url(#id)
to refer to gradients & clipping paths placed inside of the <defs>
block. For shapes and text, we'll need to use a tag: <use>
, and the syntax is slightly different:
The referenced text can still be customized by adding attributes to the use tags. <use>
is really cool & we'll see in the last example how it can be used to nest external SVGs.
SVG's coordinate systems
One of the pain points of using SVG is its coordinate system. If we naively implement the function like this:
We'll quickly find out that the cursor position does not match up with the circle inside the SVG. The circle's unit is relative to its containing SVG's viewBox.
For this reason, we'll use a function that'll translate the position correctly.
Move the circle with React
We'll need to move two circles, so let's attach some .
Note: the code for translating position has been omitted for clarity. See the codesandbox below for a complete source.
Result
Check out the final product in this . See if you can find a hidden message!
In this example, let’s explore how we can compose an SVG on the fly with React. A local pizzeria knocks on the door and asks if we could build them a fun graphic for their online ordering site. Armed with our new skills, of course we say yes!
Prerequisite
We'll need Sanity Studio for this example. Let's use the following structure:
Follow the steps below to install & initiate a new create-react-app project:
While waiting for the script to load, let's initiate the studio:
When that's all done, we'll also want to add CRA's development host to the project's CORS allowed list.
See the for further information. If you'd like a reference, see the
Writing the schema
Toppings can be placed on different pizzas, so we could have two types of documents: toppings and pizzas, containing many other toppings.
Sanity allows us to create schema in code, making it powerful & flexible, but simple to get started. In schemas
directory, create a new files:
Note that inside of the pizza document type, we create an array of references to the available toppings.
For the topping itself, we create a text field where editors can paste the SVG graphic.
In Sanity Studio, there should be a schemas/index.ts
file. Let's add the document types we've specified above.
Now that all the SVGs are placed in the Studio, it's time to build the React app. We'll use picosanity
, a smaller Sanity client.
Make a client.js
file and create the Sanity client:
Then we can import it into our React app and use it to fetch data. For simplicity, let's fetch in useEffect
and store the data inside of a useState
.
This will yield the following data:
Let's assemble a pizza from the topping SVG and the pizza's base SVG. This is where <symbol>
comes in handy.
Symbols are hidden by default and can be created with <use>
. We can still apply transform as with a standard SVG element. This is also how SVG sprite works.
Add customizer
We'll add a slider for each topping and once again simply use useState
to store users' inputs in an object.
Randomizer
The most challenging part of this exercise is placing the toppings on top of the pizza. It turns out that just placing each topping at a random position does not create a very appetizing-looking pizza!
We want to place the toppings evenly. Thankfully geometers have already figured this out ages ago! A simple Vogel spiral will come to our rescue. .
So far, so good! Let's give each topping a random rotation and vary its scale slightly, so the pizza looks more natural.
However, as soon as we add the transformation, the pizza becomes a mess... Here's what we're missing: instead of rotating from the center of itself, each topping's SVG is rotating from the center of its containing SVG (the pizza.) To fix this, we need to add the following CSS to each use
element:
With that, we now have a decent pizza customizer!
Animate with react-spring
So far, we've been relying on CSS for animation, but CSS can only take us so far. Let's create an animation where toppings fall onto the pizza whenever users update their order.
Let's use react-spring
to create a simple animation.
Note: using hook throws an error with <use/>
for some reasons, so I'm using react-spring's render props API instead.
Now it's a good time to extract <use ... /> into its component & add the animation there.
Play with ! The
We haven’t even scratched the surface of the true power of SVGs. However, the SVG format is not without flaws:
- SVGs have a verbose syntax
- Texts inside SVG do not flow naturally like they do in HTML. The solution–breaking text up manually–works for one-off graphics, but it is not scalable.
- The position & coordinate system for SVGs can be tricky
- When animating complex SVGs, performance can be an issue
However, with a little time invested learning how they work, SVGs can enrich our React websites and applications for a wide range of popular use cases.
Sanity Composable Content Cloud is the headless CMS that gives you (and your team) a content backend to drive websites and applications with modern tooling. It offers a real-time editing environment for content creators that’s easy to configure but designed to be customized with JavaScript and React when needed. With the hosted document store, you query content freely and easily integrate with any framework or data source to distribute and enrich content.
Sanity scales from weekend projects to enterprise needs and is used by companies like , , , Tata, and Figma.