How to use SVGs in React | Sanity.io guide (2024)

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.

How to use SVGs in React | Sanity.io guide (2024)

FAQs

How to use SVGs in React | Sanity.io guide? ›

We can use inline SVG directly in React components by including the SVG code as a distinct <svg> element. It involves embedding the SVG markup directly within the JSX code of a React component. In this example, we directly embed a sample SVG element into the App component.

How to use an SVG file in React? ›

We can use inline SVG directly in React components by including the SVG code as a distinct <svg> element. It involves embedding the SVG markup directly within the JSX code of a React component. In this example, we directly embed a sample SVG element into the App component.

How to use SVG in a TS file? ›

How to use svg-to-ts
  1. Binaries. ...
  2. Configuration. ...
  3. Passing arguments to the binary. ...
  4. Configure svg-to-ts over package. ...
  5. Configuration file. ...
  6. Converting to a single object ( conversionType==='object' ) ...
  7. Multiple constants - Treeshakable and typesafe with one file ( conversionType==='constants' )
Feb 18, 2024

How do I use custom SVG icons in React? ›

After finding the icon you want, hover over that icon, where you'll see options to copy that icon as SVG or JSX, and copy it as JSX. With that icon copied, create a new file under src called Globe. js . Inside of that file, we're going to create a new component called Globe and paste in our SVG within that component.

How to make SVG responsive in React? ›

In React, you can make an SVG image responsive by controlling its width and height using CSS. To make an SVG image responsive, you first need to ensure that the SVG has a viewBox attribute. The viewBox attribute specifies the aspect ratio and coordinate system of the SVG, allowing it to scale correctly.

How to use SVG in JS? ›

Code explanation:
  1. Add an id attribute to the <circle> element.
  2. Create a script within <script> tags.
  3. Get a reference to the SVG element with the getElementById() function.
  4. Change the r attribute using the setAttribute() function.
  5. Add an <input type="button"> element to run the JavaScript when clicked.

How to use SVG files? ›

Opening an SVG image with a built-in program on your computer is just as easy. Double-click the file name and you'll get a list of programs that will open it — or it'll automatically open in a compatible program.

How to use SVG in code? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

What type is an SVG in TypeScript? ›

So in TypeScript, you can represent an <svg> element in the DOM by using an intersection type (which represents a type that combines all members of two or more types, compared to a union type which represents a type that combines shared members of two or more types).

How can I read a SVG file? ›

Because SVG uses XML — a text-based markup language similar to HTML — any modern web browser can display an SVG file. Just drag your SVG file to a browser like Chrome, Firefox, Safari or Microsoft Edge and the image should appear in a new tab.

How to use icons in React? ›

[React] - How to import icons into React
  1. Find the specific icon you want to use on the icon library's website or documentation. Each icon should have a unique class name.
  2. Add the icon to your component using the library's icon component or HTML tag (depending on the library).

How to use SVG as component in React Vite? ›

Enter vite-plugin-svgr

js : import svgr from 'vite-plugin-svgr' export default { // ... plugins: [svgr()], // ... } And boom, you get your expected behavior!

Is it better to use SVG or PNG in React? ›

SVG images are vector-based, which means they can be scaled up or down without losing quality. This makes them an excellent choice for responsive web design, where images need to adapt to different screen sizes and resolutions. PNG images, on the other hand, are raster-based and can lose quality when scaled.

How to use SVG as React component in next js? ›

For NextJS ⛷️
  1. //next. ...
  2. import React from "react"; import { ReactComponent as MailIcon } from "@assets/icons/auth/mail.svg"; function Page() { return ( <div> {/* Utilizing the configured MailIcon component */} <MailIcon strokeWidth={1.2} /> </div> ); } export default Page;

How do I create a dynamic SVG in React? ›

Method 1: Using template literals and data-URI

Copy the SVG contents within a JavaScript template literal `...` and replace the text you want to change dynamically. In the following example to: ${amount}&#8467; Convert the string into a data-uri with "data:image/svg+xml;base64," + btoa(source) and use it as image URL.

How do I import SVG animation into React? ›

I.) React websites based on Create React App
  1. Step 1.) Add SVG: Add the exported SVG into your project - stopwatch. ...
  2. Step 2.) Create Custom Component: Add your wrapper component ( Stopwatch.jsx in this example) with the structure below: ...
  3. Step 3.) Move Javascript Code: ...
  4. Step 4.) Handle Style Tags:
Mar 2, 2023

How do I import SVG into HTML? ›

SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.

How to use SVG in vite React? ›

Installation…
  1. import { defineConfig } from "vite";
  2. import react from "@vitejs/plugin-react";
  3. import svgr from "vite-plugin-svgr";
  4. export default defineConfig({ // …
  5. plugins: [ react(), svgr()], });
Apr 3, 2024

How to import SVG as React component in NextJS? ›

For NextJS ⛷️
  1. //next. ...
  2. import React from "react"; import { ReactComponent as MailIcon } from "@assets/icons/auth/mail.svg"; function Page() { return ( <div> {/* Utilizing the configured MailIcon component */} <MailIcon strokeWidth={1.2} /> </div> ); } export default Page;

Top Articles
Ledger - Web3 Wallets - Alchemy
Buy Gold & Silver Bullion Online | Free Shipping - JM Bullion
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 5823

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.