Skip to content

Instantly share code, notes, and snippets.

@Noveller
Forked from rich-97/AvatarUpload.tsx
Created December 26, 2022 20:23
Show Gist options
  • Save Noveller/8409824801cd779305e3863236d2f10e to your computer and use it in GitHub Desktop.
Save Noveller/8409824801cd779305e3863236d2f10e to your computer and use it in GitHub Desktop.
React - Avatar Upload with Ant Design
import React, { useState, useCallback } from 'react';
import { Avatar, Button, Upload } from 'antd';
import { DownloadOutlined, UserOutlined } from '@ant-design/icons';
import { fileToBase64 } from "../../utils";
interface Props {
label: string,
buttonText: string,
action: string,
avatarIcon?: React.ReactElement,
avatarDefaultImage?: string,
};
const AvatarUpload: React.FC<Props> = ({
label,
buttonText,
action,
avatarIcon,
avatarDefaultImage,
}) => {
const [image, setImage] = useState(avatarDefaultImage);
const handleOnChangeImage = useCallback(
(info) => {
if (info.file.status === "done" && image === "") {
fileToBase64(info.file.originFileObj).then((fileBase64) => {
setImage(fileBase64);
});
}
if (info.file.status === "removed" && image !== "") {
setImage(avatarDefaultImage);
}
},
[image]
);
return (
<>
<div style={{ marginBottom: "24px" }}>
<p>{label}</p>
<Avatar size={80} icon={avatarIcon} src={image} />
</div>
<div style={{ marginBottom: "61px" }}>
<Upload
action={action}
name="file"
accept="image/*"
onChange={handleOnChangeImage}
>
<Button icon={<DownloadOutlined />} disabled={image !== ""}>
{buttonText}
</Button>
</Upload>
</div>
</>
);
};
AvatarUpload.defaultProps = {
avatarIcon: <UserOutlined />,
avatarDefaultImage: "",
};
export default AvatarUpload;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment