Frameworks

SVG Patterns in React, Vue & Angular

Component patterns, hooks, directives, and utilities for integrating SVG backgrounds into your favourite framework.

10 min read Jan 2026 3 PDF downloads

React: The SvgPattern Component

Build a reusable <SvgPattern> React component that accepts colour, scale, and shape props and dynamically constructs the SVG data URI. Use useMemo to memoize the base64 string — it only recalculates when props change, avoiding expensive string operations on every render.

function SvgPattern({ fg = '#6366f1', bg = '#f5f5ff', size = 20 }) {
  const dataUri = useMemo(() => {
    const svg = `<svg xmlns="..." width="${size}" height="${size}">
      <rect fill="${bg}" width="100%" height="100%"/>
      <circle cx="${size/2}" cy="${size/2}" r="${size/6}" fill="${fg}"/>
    </svg>`;
    return `url('data:image/svg+xml;base64,${btoa(svg)}')`;
  }, [fg, bg, size]);

  return <div style={{ backgroundImage: dataUri }} />;
}

Vue 3: Computed Pattern Composable

In Vue 3, create a usePattern() composable that accepts reactive refs for colours and returns a computed CSS style object. The composable can be shared across components and reacts automatically to theme changes or user input.

Angular: PatternDirective

Create an Angular directive [svgPattern] that accepts a pattern config input and sets the host element's background-image style. Use the DomSanitizer service to mark the data URI as safe — Angular's template sanitizer strips data URIs by default.

CSS-in-JS Integration (Styled Components / Emotion)

With CSS-in-JS, pattern styles live next to component code. Create a patternBackground style factory function that accepts theme tokens and returns a CSS object. This integrates perfectly with styled-system theme shapes and keeps pattern logic out of global stylesheets.

Server-Side Rendering Considerations

Data URIs are static strings — they render identically on server and client, making SVG patterns SSR-safe. There's no hydration mismatch risk. For patterns that depend on dynamic values (user preferences, API data), generate the data URI on the server and inject it into the initial HTML as a CSS custom property.

TypeScript Pattern Types

Define a TypeScript interface for pattern configurations: PatternConfig { type: PatternType; fg: CSSColor; bg: CSSColor; size: number; opacity?: number }. This enables autocomplete in editors and catches invalid colour formats at compile time. Combine with branded types (type CSSColor = string & { _brand: 'color' }) for even stricter validation.

Testing Pattern Components

Unit test your pattern components by checking the computed background-image style value. For visual regression testing, use Chromatic or Percy — they snapshot the rendered pattern and alert you to any unexpected visual changes. Pattern components are excellent candidates for visual regression tests because their output should be 100% deterministic.