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 |
|---|---|---|
|
| The base64 string of the avatar image to display initially or controlled externally. |
| (value: string) => void (optional) | Callback function called with the new base64 string when the avatar changes or is removed. |
Parameters
value: An optional string representing the base64-encoded avatar image. When provided, the component shows this image initially.onChange: An optional callback triggered whenever the avatar image changes, passing the new base64 string or an empty string if removed.
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
avatarBase64Str: Astringstate holding the current avatar image as a base64-encoded string.
Functions and Methods
handleChange: ChangeEventHandler<HTMLInputElement>
Purpose: Handles file input changes when the user selects a new image file.
Parameters:
ev- the change event from the file input.Logic:
Extracts the first file from the input.
Validates the file extension against accepted image formats using a regex.
Converts the file to a base64 string asynchronously via
transformFile2Base64.Updates the local state
avatarBase64Strand triggersonChangecallback with the new string.Clears the file input value to allow re-uploading the same file if needed.
Usage: Bound to the
onChangeevent of the hidden file input element.
handleRemove: () => void
Purpose: Clears the current avatar image.
Logic:
Resets
avatarBase64Strto an empty string.Calls
onChangewith an empty string to notify the parent of removal.
Usage: Bound to the remove button's
onClickevent.
useEffect
Purpose: Synchronizes local state
avatarBase64Strwith thevalueprop if it changes externally.Dependency: Runs whenever
valuechanges.Effect: Sets
avatarBase64Strto the newvalue.
Implementation Details
File-to-base64 Conversion: Uses a utility function
transformFile2Base64(imported from@/utils/file-util) to convert uploaded image files to base64 strings asynchronously.File Validation: Uses a regex
/.(jpg|jpeg|png|webp|bmp)$/ito restrict accepted file types.UI Composition:
When no avatar is selected, a dashed border box with an upload icon and localized text is shown.
When an avatar is present, it displays the image inside a custom
Avatarcomponent.An edit pencil icon appears on hover, indicating the ability to change the avatar.
A remove button (with an X icon) allows clearing the avatar.
Accessibility: The remove button has an
aria-labelfor screen readers.Styling: Uses Tailwind CSS classes for layout, spacing, borders, and hover effects.
Localization: Uses the
useTranslationhook fromreact-i18nextfor multi-language support on texts like "upload" and photo tips.
Interaction with Other Modules
transformFile2Base64(from@/utils/file-util): Converts image files to base64 strings.UI Components (
Avatar,AvatarImage,AvatarFallback,Button,Input): Custom reusable components for consistent UI elements.Icons (
Pencil,Upload,XIconfromlucide-react): For visual cues on upload, edit, and removal actions.Localization (
react-i18next): For translated UI strings.Parent Components: Provide the initial avatar base64 string via
valueand handle updates viaonChange.
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.