SVG in React, Vue, Svelte and Astro

Use SVG in React, Vue, Svelte and Astro: inline markup, data-driven shapes, refs, safe HTML injection, and Astro's SVG components, with trade-offs for each.

Every major framework can render SVG, because inline SVG is just more elements in the DOM. The differences are in how each framework names attributes, binds data, gives you access to a node, and handles raw SVG strings. This guide covers the practical parts for React, Vue, Svelte and Astro.

Four ways to bring SVG into a component

  1. Write it inline. The SVG is part of the template. You can style it with the page’s CSS, bind data to it and script it.
  2. Reference a file with <img src="logo.svg">. It is cached separately and simple, but it cannot see your page’s CSS and scripts do not run in it. See SVG as an image limits for details.
  3. Import it as a component. A build step turns a .svg file into component code or inlined markup. Astro does this natively. In other setups it typically takes a build plugin, which this guide does not cover.
  4. Inject a string with dangerouslySetInnerHTML, v-html or {@html}. Use this only for trusted content.

Choose inline for anything data-driven or interactive, a file reference for static artwork that never needs styling from the page, and an imported component for icons you want to recolor with CSS.

React

React supports all built-in browser SVG elements. A few differences from raw SVG apply:

  • Props use camelCase, as the React docs state for DOM props in general. Write strokeWidth, not stroke-width, and className, not class.
  • Namespaced attributes are written without the colon: xlink:href becomes xlinkHref, and xml:space becomes xmlSpace.
  • The style prop takes an object with camelCase keys.

A data-driven chart is plain JSX:

function BarChart({ data, width = 240, height = 120 }) {
  const max = Math.max(...data.map((d) => d.value));
  const slot = width / data.length;

  return (
    <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Sales by quarter">
      {data.map((d, i) => {
        const h = (d.value / max) * (height - 20);
        return (
          <rect
            key={d.label}
            x={i * slot + 6}
            y={height - h}
            width={slot - 12}
            height={h}
            fill="#1f3fe0"
          />
        );
      })}
    </svg>
  );
}

Here is the markup that component renders for three data points. Edit it to see how the numbers map to shapes.

Refs. To measure a path or call another DOM API, attach a ref with useRef. React sets ref.current after it commits the node, so it is null during the first render. Read refs in event handlers or in an Effect, not while rendering. The docs also warn against modifying DOM nodes that React manages, because that can leave React’s picture of the page out of step with the real one. Setting attributes on your own <svg> through a ref is fine for things React never renders, but prefer props and state for anything React already controls.

Raw strings. dangerouslySetInnerHTML takes { __html: string }. React’s own docs say that with untrusted input it is trivial to introduce an XSS vulnerability, and that it cannot be combined with children. Sanitize first, or avoid it. See SVG security.

Recoloring icons in any framework

An inline SVG that uses fill="currentColor" takes its color from the surrounding text, which is why passing fill="currentColor" in the Astro example below is useful. The same trick works in every framework. The playground shows the idea in plain markup and CSS: change the color values and both icons follow.

Vue

Vue templates use v-bind, shortened to :, to set attributes from data. In single-file components, attribute names keep their case, so viewBox and stroke-width appear as they do in SVG files. (Vue’s docs warn that browsers lowercase attribute names in in-DOM templates, which does not affect single-file components.) When a bound value is null or undefined, Vue removes the attribute.

<script setup>
import { computed } from "vue";

const props = defineProps({ data: Array });
const max = computed(() => Math.max(...props.data.map((d) => d.value)));
</script>

<template>
  <svg viewBox="0 0 240 120" role="img" aria-label="Sales by quarter">
    <rect
      v-for="(d, i) in data"
      :x="i * 80 + 6"
      :y="120 - (d.value / max) * 100"
      width="68"
      :height="(d.value / max) * 100"
      fill="#1f3fe0"
    />
  </svg>
</template>

For direct DOM access, use a template ref. In Vue 3.5 and later, useTemplateRef("name") pairs with ref="name" on the element. The docs say the ref is only available after the component mounts, so it is empty on first render and can become empty again if a v-if removes the element. Guard for the empty case. In versions before 3.5, declare a ref(null) whose name matches the ref attribute.

v-html renders a string as HTML. Vue’s docs warn that it can easily lead to XSS vulnerabilities and say to use it only on trusted content, never on user-provided content.

Svelte

Svelte writes attribute values with braces, <rect x={x} y={y} />, and omits an attribute whose value is null or undefined. Event handlers are attributes that start with on, like onclick, and are case sensitive.

<script>
  let { data } = $props();
  const max = $derived(Math.max(...data.map((d) => d.value)));
</script>

<svg viewBox="0 0 240 120" role="img" aria-label="Sales by quarter">
  {#each data as d, i}
    <rect
      x={i * 80 + 6}
      y={120 - (d.value / max) * 100}
      width="68"
      height={(d.value / max) * 100}
      fill="#1f3fe0"
    />
  {/each}
</svg>

Use bind:this={node} to get the element. Svelte documents the value as undefined until the component is mounted, so read it inside an effect or an event handler, not during component setup. The {@html} tag injects raw markup. Svelte warns you to escape the string or use only values you control to prevent XSS.

Astro

Native HTML tags such as <svg> work in .astro files directly, and Astro’s docs say images rendered with HTML tags are copied into the build as-is. Inline SVG there is plain HTML with no client JavaScript.

Since Astro 5.7.0, you can import a local .svg file and use it as a component. Astro inlines the file’s content into the HTML. Attributes you pass, such as width, height, fill and stroke, are applied to the <svg> element and override the same attribute in the file.

---
import Logo from "../assets/logo.svg";
---

<Logo width={64} height={64} fill="currentColor" />

Two limits from Astro’s docs: SVG components are not available inside UI framework components (you can pass one into a framework component from a .astro file), and Astro’s own page about importing SVG as an asset is inconsistent about whether the plain import returns a URL string or an object with a src property. Check what your installed version returns before you depend on it.

For interactivity, a framework component in Astro renders as HTML with no JavaScript unless you add a client:* directive. client:visible waits until the component enters the viewport, client:idle waits for the browser to be idle, and client:load hydrates immediately. A static chart needs no directive. A chart with tooltips might use client:visible.

Trade-offs to weigh

  • Inline SVG grows your HTML. A large illustration repeated on many pages is better as a cached file. A small, interactive or themable icon is better inline.
  • Duplicate ids. If the same inline SVG appears twice on a page, any id inside it, such as a gradient or filter reference, is no longer unique. Generate ids per instance or avoid ids where you can. Check how your optimizer handles ids, as described in SVG optimization.
  • Accessibility does not come free. Add role="img" with a label, or use <title>, on meaningful graphics, and hide decorative ones. See SVG accessibility.
  • Animation. CSS and SMIL work in any framework. Script-driven animation needs a ref and cleanup when the component unmounts. See SVG animation.

Next, apply these patterns to a full example in interactive infographics, or revisit the raw DOM APIs in SVG with JavaScript.

Sources

Checked against these references on 2026-11-21.