Examples

Sample landscape Sample architecture Sample nature
Test-targeted image

testId="sample-img" → data-pw="sample-img" on the <img> element

SVG inlining

inlineSvg → the fetched markup renders as an inline <svg> host

SVG inlining with transformSvg

transformSvg rewrites the fetched markup before it is inlined


Documentation

An image component with automatic fallback. If the primary src fails to load (onerror), it switches to the fallback URL. The fallback only triggers once (won't loop if fallback also fails). Supports hover styling for interactive image use cases, and opt-in SVG inlining (inlineSvg / transformSvg) so icons can be recoloured by page CSS or a transform hook.

Usage

<script>
  import { Img } from '@juspay/svelte-ui-components';
</script>

<Img src={'...'} alt={'...'} />

Props

Prop Type Required Default Description
src string Yes - The primary image URL to display.
alt string Yes - Alt text for the image.
fallback string | null No - Fallback image URL. If the primary src fails to load (onerror), the component switches to this URL.
testId string No - Test identifier applied as data-pw attribute on the <img> element for Playwright test selectors.
classes string No - CSS class string applied to the component's top-level element. Useful for theming — define classes with CSS variable overrides and pass them to create variant styles.
inlineSvg boolean No false Fetch .svg / data:image/svg+xml sources and inline their markup into an <svg> host so page CSS (currentColor, fill/stroke overrides) applies. Non-SVG sources always render the plain <img>. If fetching or parsing fails, the component falls back to the plain <img> (and from there to the regular fallback/onerror chain).
transformSvg (svg: string) => string No - Hook to rewrite the fetched SVG markup before it is inlined (e.g. recolour hardcoded fills). Providing a transform implies inlineSvg. The inlining effect re-runs when the prop identity changes, so a closure over reactive state (e.g. a theme colour) re-renders live. Root attributes the transform adds are treated as caller intent and copied to the host even when outside the fetched-attribute allowlist (see SVG inlining below). JS-only prop (not exposed as a web-component attribute).

SVG inlining

With inlineSvg (or any transformSvg), SVG sources are fetched and their markup is inlined into an <svg> host element instead of an <img>. This makes the icon stylable by page CSS — fill: currentColor, theme variables, and selector-based recolouring all work, which an external <img> cannot do.

<!-- Inline so the icon picks up currentColor from its parent -->
<Img src={'/icons/refresh.svg'} alt="" inlineSvg />

<!-- Recolour hardcoded fills, live-reactive to a theme store -->
<Img
  src={'/icons/wallet.svg'}
  alt="Wallet"
  transformSvg={(svg) => svg.replaceAll('#2b2b2b', themeColor)}
/>

Behaviour notes:

  • Non-SVG sources ignore both props and always render the plain <img>.
  • A failed fetch/parse for a given URL falls back to the plain <img> for that URL (which then drives the normal fallback/onerror chain); a changed src gets a fresh inlining attempt.
  • The fetched document is treated as untrusted content: only an allowlist of presentational, geometry, and accessibility attributes is copied from its root onto the live <svg> host — xmlns, xmlns:xlink, viewBox, width, height, x, y, preserveAspectRatio, fill/fill-*, stroke/stroke-*, clip-rule, color, opacity, overflow, role, focusable, and aria-*. Anything else from the fetched file — event handlers (onload, onclick, …), id, style, class, data-* — never reaches the live element, so a hostile SVG cannot inject script or clobber the data-pw test hook.
  • Child elements are sanitized before adoption, not inlined verbatim: <script> and <foreignObject> subtrees are removed outright, every on* attribute is stripped at any depth, and href/xlink:href/src values pointing at javascript: are dropped. Without this, the root allowlist alone would be bypassable — the root is not where a hostile file would put its payload. Everything else about a child (its geometry, styling, id, class) survives untouched.
  • Root attributes that your own transformSvg hook adds (names not present on the fetched root) are caller intent and pass through unfiltered — e.g. a transform can stamp a data-* marker on the host.
  • Accessibility: the <svg> host gets role="img" + aria-label when alt is non-empty, and aria-hidden="true" when alt is empty (decorative).
  • All CSS variables below apply to the inlined <svg> host exactly as they do to the <img>.

CSS Variables

Override these custom properties to theme the component.

Variable Default CSS Property Description
--image-object-fit - object-fit Object-fit of the image (contain, cover, etc.).
--image-height 24px height Height of the image.
--image-width 24px width Width of the image.
--image-max-width - max-width Maximum width: a length, a percentage, or none.
--image-max-height - max-height Maximum height: a length, a percentage, or none.
--image-padding 0px padding Padding around the image.
--image-border-radius 0px border-radius Corner rounding of the image.
--image-margin 0px margin Margin around the image.
--image-filter none filter CSS filter applied to the image (e.g., grayscale, brightness).
--image-background - background Background behind the image.
--image-border - border Border of the image.
--image-transition - transition Transition animation for hover effects.
--image-hover-background var(--image-background) background Background on hover.
--image-hover-border var(--image-border) border Border on hover.

Capping an image to its container

--image-width and --image-height size the image; --image-max-width and --image-max-height cap it. To show an image at its own size but never larger than the box it sits in, size it with auto and cap it with 100%:

<Img src={photo} alt="Photo" classes="preview" />

<style>
  :global(.preview) {
    --image-width: auto;
    --image-height: auto;
    --image-max-width: 100%;
    --image-max-height: 100%;
    --image-object-fit: contain;
  }
</style>
  • A cap wins over the size token on the same axis, and with the 24px default a cap changes only the axis it names (--image-max-width: 12px renders 12px by 24px). Size with auto, as above, to keep the ratio.
  • A percentage resolves against the container as for any max-width; a percentage max-height needs a container with a definite height. Both apply to the <img> and to the inlined <svg>, and cross the <sui-img> shadow root like the other variables.
  • With neither variable set nothing changes: the image computes what it did before, beside any max-width or max-height rule of your own. The caps sit in a cascade layer, svelte-ui-img, the first the library adds to a page's layer list, so a rule outside a layer decides over them whatever its selector and whichever stylesheet loads first, img { max-width: 100% }, * { … } and :where(img) { … } included, and the variable is then ignored. A reset in a cascade layer, as Tailwind 4's preflight is, gives way to a variable you set when its layer is first named before the library's (none opts out of it) and decides when neither is set; one first named after the library's decides in every case.

Events

Event Type Description
onerror () => void Fires when the image fails to load and no fallback is available, or when the fallback image itself also fails to load. Does not fire when the primary image fails but a valid fallback URL exists — the component silently switches to the fallback instead.
onimageerror (event: Event) => void Opt-in native error event after the same fallback chain. The legacy onerror stays zero-argument.

Web Component

Tag: <sui-img>

<sui-img src="/photo.jpg" alt="Description" fallback="/fallback.jpg" test-id="my-img"></sui-img>

onerror is a JS-property callback only (img.onerror = () => ...) and does not dispatch a DOM event: error is already HTMLElement's own native event, so an img.addEventListener('error', ...) listener still sees the real one, and adding a second, synthetic one under the same name would double-deliver it to that same listener.

Native consumer integration

nativeAttrs forwards typed native attributes to the actual control/media element. Use dedicated props for component-owned state, source, classes, events, and test hooks; those props retain precedence over an attribute spread. element is a bindable native reference for Svelte controllers that measure, focus, animate, or manage media. unstyled renders the native element without layout wrappers or component appearance, so a host's centralized recipe can preserve its composition. Default rendering and appearance remain unchanged when these props are omitted.

Image nativeAttrs includes loading, intrinsic width/height, decoding, fetchpriority, srcset, and sizes. They render with the image, including during SSR, rather than being applied after the browser may have started a request. onload receives the native load event. The existing onerror/fallback chain retains ownership of source failures. Native-image attributes apply to the image path; SVG inlining uses its separate SVG semantics.

Web components expose onimageload / the imageload event for image loads; the native host onload accessor remains intact.

<sui-img> also exposes onimageerror and dispatches imageerror; its legacy onerror remains callback-only. See 4.x compatibility.