index.js
62 lines
| 1 | import {useCallback, useState, useEffect} from 'react'; |
| 2 | import {__} from '@wordpress/i18n'; |
| 3 | import {useDropzone} from 'react-dropzone'; |
| 4 | |
| 5 | import './style.scss'; |
| 6 | |
| 7 | const AvatarControl = ({url, file, onChange}) => { |
| 8 | const onDrop = useCallback((acceptedFiles) => { |
| 9 | onChange(acceptedFiles[0]); |
| 10 | }, []); |
| 11 | |
| 12 | const {getRootProps, getInputProps, isDragActive} = useDropzone({ |
| 13 | onDrop, |
| 14 | accept: 'image/jpeg, image/png, image/gif', |
| 15 | maxFiles: 1, |
| 16 | }); |
| 17 | const [previewSrc, setPreviewSrc] = useState(url); |
| 18 | |
| 19 | useEffect(() => { |
| 20 | if (file) { |
| 21 | const reader = new window.FileReader(); |
| 22 | reader.readAsDataURL(file); |
| 23 | reader.onloadend = function () { |
| 24 | setPreviewSrc(reader.result); |
| 25 | }; |
| 26 | } |
| 27 | }, [file]); |
| 28 | |
| 29 | return ( |
| 30 | <div className="give-donor-dashboard-avatar-control"> |
| 31 | <label className="give-donor-dashboard-avatar-control__label">{__('Avatar', 'give')}</label> |
| 32 | <div className="give-donor-dashboard-avatar-control__input" {...getRootProps()}> |
| 33 | <input {...getInputProps()} /> |
| 34 | <div className="give-donor-dashboard-avatar-control__preview"> |
| 35 | <img src={previewSrc}/> |
| 36 | </div> |
| 37 | <div |
| 38 | className={`give-donor-dashboard-avatar-control__dropzone${ |
| 39 | isDragActive ? ' give-donor-dashboard-avatar-control__dropzone--highlight' : '' |
| 40 | }`} |
| 41 | > |
| 42 | <div className="give-donor-dashboard-avatar-control__instructions"> |
| 43 | {isDragActive ? ( |
| 44 | <p>{__('Drop the image here...', 'give')}</p> |
| 45 | ) : ( |
| 46 | <p> |
| 47 | {__('Drag image here to set', 'give')} <br/> |
| 48 | {__('avatar or', 'give')}{' '} |
| 49 | <span className="give-donor-dashboard-avatar-control__select-link"> |
| 50 | {__('find image', 'give')} |
| 51 | </span> |
| 52 | </p> |
| 53 | )} |
| 54 | </div> |
| 55 | </div> |
| 56 | </div> |
| 57 | </div> |
| 58 | ); |
| 59 | }; |
| 60 | |
| 61 | export default AvatarControl; |
| 62 |