import React, { useRef } from 'react'; import Button from '@material-ui/core/Button'; import CloudUpload from '@material-ui/icons/CloudUpload'; import { getLocalFileUrl } from '../../utils/files'; interface PropTypes { callback: (fileUrl: string, file: File) => void; } const FileUpload: React.FC = ({ callback, children }) => { const inputRef = useRef(null); const handleChange = (event: React.ChangeEvent) => { const files = event.target?.files; if (files?.length) { const file = files[0]; getLocalFileUrl(file).then(url => callback(url, file)); }; }; const handleClick = () => { if (inputRef?.current) inputRef.current.click(); }; const child = children && React.Children.only(children); const defaultButton = ( ); return ( <> { React.isValidElement(child) ? React.cloneElement(child, { onClick: handleClick }) : defaultButton } ); }; export default FileUpload;