avatar-upload.tsx


Overview

avatar-upload.tsx is a React functional component designed to provide a user interface for uploading, displaying, and removing an avatar image. It supports image files in common formats (jpg, jpeg, png, webp, bmp) and converts uploaded images into base64 strings for immediate preview and easy data handling by parent components.

The component uses React hooks for state management and side effects, integrates with an internationalization library for localized text, and leverages custom UI components (Avatar, Button, Input) for consistent styling. It also provides accessibility considerations such as aria-labels.


Component: AvatarUpload

Description

AvatarUpload is a forward-ref React component that renders an avatar image upload interface. It handles file input changes, validates image types, converts images to base64 strings, and allows users to remove the selected avatar.

Props

Prop

Type

Description

value

string (optional)

The base64 string of the avatar image to display initially or controlled externally.

onChange

(value: string) => void (optional)

Callback function called with the new base64 string when the avatar changes or is removed.

Parameters

Returns

A JSX element rendering the avatar upload UI.

Usage example

import { useState } from 'react';
import { AvatarUpload } from './avatar-upload';

function ProfileSettings() {
  const [avatar, setAvatar] = useState<string>('');

  return (
    <AvatarUpload
      value={avatar}
      onChange={(newAvatar) => setAvatar(newAvatar)}
    />
  );
}

Internal State


Functions and Methods

handleChange: ChangeEventHandler<HTMLInputElement>

handleRemove: () => void

useEffect


Implementation Details


Interaction with Other Modules


Visual Diagram

componentDiagram
    component AvatarUpload {
        +props: AvatarUploadProps
        +state: avatarBase64Str:string
        +handleChange(ev):void
        +handleRemove():void
        +useEffect()
    }

    component transformFile2Base64
    component Avatar
    component Button
    component Input
    component useTranslation

    AvatarUpload --> transformFile2Base64 : calls
    AvatarUpload --> Avatar : renders
    AvatarUpload --> Button : renders
    AvatarUpload --> Input : renders
    AvatarUpload --> useTranslation : uses

Summary

The AvatarUpload component provides an intuitive interface for users to upload and manage avatar images within a React application. It converts image files to base64 for immediate preview, supports removal of the avatar, and integrates localization and accessibility best practices. This component is designed to be reusable and customizable via props and fits within a broader UI system through its use of shared UI components and utilities.