palletface

Integrations

How do I generate a fallback avatar in React?

Use the user's uploaded photo when it exists. Otherwise, pass a stable user ID to palletface and encode the SVG string as an image URL. This component works during server rendering and in the browser. It assumes the user's name is already visible next to the image.

import { palletface } from 'palletface'

export function ProfileAvatar({ userId, photoUrl }) {
  const src = photoUrl || `data:image/svg+xml;charset=utf-8,${encodeURIComponent(palletface(userId))}`
  return <img src={src} alt="" width={80} height={80} />
}

Browser with a bundler

Add <img id="avatar" width="80" height="80" alt="Ada's avatar"> to the page.

import { palletface } from 'palletface'

const svg = palletface('user-123', { style: 'pixel-letter', name: 'Ada' })
document.getElementById('avatar').src =
  `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`

If your Content Security Policy disallows data: in img-src, use a URL for the SVG on your own server. Use alt="" when a visible name already labels the avatar.

Browser without a bundler

Serve node_modules/palletface/dist/palletface.js next to your HTML. The file exposes Palletface.

<img id="avatar" width="80" height="80" alt="Ada's avatar">
<script src="./palletface.js"></script>
<script>
  const { palletface } = Palletface
  const svg = palletface('user-123')
  document.getElementById('avatar').src =
    `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`
</script>

Server response

Return the SVG as image/svg+xml. This example uses the Fetch Response API.

import { palletface } from 'palletface'

export function avatarResponse(userId) {
  return new Response(palletface(userId), {
    headers: { 'Content-Type': 'image/svg+xml; charset=utf-8' },
  })
}