Created
July 19, 2020 20:04
-
-
Save rich-97/095681e76f5ed03549812a534c3d6c6a to your computer and use it in GitHub Desktop.
React - Avatar Upload with Ant Design
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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