{"slug":"avatar","title":"Avatar","description":"Using the avatar machine in your project.","contentType":"component","framework":"react","content":"The Avatar component is a React component that represents a user avatar or\nprofile picture. It displays an image or initials within container.\n\nAvatar provides support for fallback text or elements when the image fails to\nload, or when the image is not provided.\n\n## Resources\n\n\n[Latest version: v1.31.0](https://www.npmjs.com/package/@zag-js/avatar)\n[Logic Visualizer](https://zag-visualizer.vercel.app/avatar)\n[Source Code](https://github.com/chakra-ui/zag/tree/main/packages/machines/avatar)\n\n\n\n## Installation\n\nTo use the avatar machine in your project, run the following command in your\ncommand line:\n\n```bash\nnpm install @zag-js/avatar @zag-js/react\n# or\nyarn add @zag-js/avatar @zag-js/react\n```\n\n## Anatomy\n\nTo set up the avatar correctly, you'll need to understand its anatomy and how we\nname its parts.\n\n> Each part includes a `data-part` attribute to help identify them in the DOM.\n\n\n\n## Usage\n\nFirst, import the avatar package into your project\n\n```jsx\nimport * as avatar from \"@zag-js/avatar\"\n```\n\nThe avatar package exports two key functions:\n\n- `machine` — The state machine logic for the avatar widget.\n- `connect` — The function that translates the machine's state to JSX attributes\n  and event handlers.\n\n> You'll also need to provide a unique `id` to the `useMachine` hook. This is\n> used to ensure that every part has a unique identifier.\n\nNext, import the required hooks and functions for your framework and use the\navatar machine in your project 🔥\n\n```jsx\nimport * as avatar from \"@zag-js/avatar\"\nimport { useMachine, normalizeProps } from \"@zag-js/react\"\n\nfunction Avatar() {\n  const service = useMachine(avatar.machine, { id: \"1\" })\n\n  const api = avatar.connect(service, normalizeProps)\n\n  return (\n    <div {...api.getRootProps()}>\n      <span {...api.getFallbackProps()}>PA</span>\n      <img alt=\"PA\" src={src} {...api.getImageProps()} />\n    </div>\n  )\n}\n```\n\n### Listening for loading status changes\n\nWhen the image has loaded or failed to load, the `onStatusChange` callback is\ninvoked.\n\n```jsx {2}\nconst service = useMachine(avatar.machine, {\n  onStatusChange(details) {\n    // details => { status: \"error\" | \"loaded\" }\n  },\n})\n```\n\n## Styling guide\n\nEarlier, we mentioned that each avatar part has a `data-part` attribute added to\nthem to select and style them in the DOM.\n\n```css\n[data-scope=\"avatar\"][data-part=\"root\"] {\n  /* Styles for the root part */\n}\n\n[data-scope=\"avatar\"][data-part=\"image\"] {\n  /* Styles for the image part */\n}\n\n[data-scope=\"avatar\"][data-part=\"fallback\"] {\n  /* Styles for the fallback part */\n}\n```\n\n## Creating Component\n\nCreate your avatar component by abstracting the machine into your own component.\n\n### Usage\n\n```tsx\nimport { Avatar } from \"./your-avatar\"\n\nfunction Demo() {\n  return (\n    <Avatar\n      src=\"https://avatars.githubusercontent.com/u/139426\"\n      name=\"John Doe\"\n    />\n  )\n}\n```\n\n### Implementation\n\nUse the the `splitProps` utility to separate the machine's props from the\ncomponent's props.\n\n```tsx\nimport * as avatar from \"@zag-js/avatar\"\nimport { useMachine, normalizeProps } from \"@zag-js/react\"\n\nexport interface AvatarProps extends Omit<avatar.Context, \"id\"> {\n  /**\n   * The src of the avatar image\n   */\n  src?: string\n  /**\n   * The srcSet of the avatar image\n   */\n  srcSet?: string\n  /**\n   * The name of the avatar\n   */\n  name: string\n}\n\nfunction Avatar(props: AvatarProps) {\n  const [machineProps, localProps] = avatar.splitProps(props)\n\n  const service = useMachine(avatar.machine, {\n    id: useId(),\n    ...machineProps,\n  })\n\n  const api = avatar.connect(service, normalizeProps)\n\n  return (\n    <div {...api.getRootProps()}>\n      <span {...api.getFallbackProps()}>{getInitials(localProps.name)}</span>\n      <img\n        alt=\"PA\"\n        src={localProps.src}\n        srcSet={localProps.srcSet}\n        {...api.getImageProps()}\n      />\n    </div>\n  )\n}\n\nfunction getInitials(name: string) {\n  return name\n    .split(\" \")\n    .map((word) => word[0])\n    .join(\"\")\n}\n```\n\n## Methods and Properties\n\n### Machine Context\n\nThe avatar machine exposes the following context properties:\n\n**`onStatusChange`**\nType: `(details: StatusChangeDetails) => void`\nDescription: Functional called when the image loading status changes.\n\n**`ids`**\nType: `Partial<{ root: string; image: string; fallback: string; }>`\nDescription: The ids of the elements in the avatar. Useful for composition.\n\n**`id`**\nType: `string`\nDescription: The unique identifier of the machine.\n\n**`getRootNode`**\nType: `() => ShadowRoot | Node | Document`\nDescription: A root node to correctly resolve document in custom environments. E.x.: Iframes, Electron.\n\n**`dir`**\nType: `\"ltr\" | \"rtl\"`\nDescription: The document's text/writing direction.\n\n### Machine API\n\nThe avatar `api` exposes the following methods:\n\n**`loaded`**\nType: `boolean`\nDescription: Whether the image is loaded.\n\n**`setSrc`**\nType: `(src: string) => void`\nDescription: Function to set new src.\n\n**`setLoaded`**\nType: `VoidFunction`\nDescription: Function to set loaded state.\n\n**`setError`**\nType: `VoidFunction`\nDescription: Function to set error state.\n\n### Data Attributes\n\n**`Image`**\n\n**`data-scope`**: avatar\n**`data-part`**: image\n**`data-state`**: \"visible\" | \"hidden\"\n\n**`Fallback`**\n\n**`data-scope`**: avatar\n**`data-part`**: fallback\n**`data-state`**: \"hidden\" | \"visible\"","package":"@zag-js/avatar","editUrl":"https://github.com/chakra-ui/zag/edit/main/website/data/components/avatar.mdx"}