Built Twitter Like App - 20

Add Image Upload Function

  1. Install dropzone
  2. Add component ImageUpload
  3. Modify EditModal

Install Dropzone

1
npm install react-dropzone

Add component ImageUpload

Add file component/ImageUpload.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Image from 'next/image';
import { useCallback, useState } from 'react';
import { useDropzone } from 'react-dropzone';

interface ImageUploadProps {
onChange: (base64: string) => void;
label: string;
value?: string;
disabled?: boolean;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
onChange,
label,
value,
disabled
}) => {
const [base64, setBase64] = useState(value);
const handleChange = useCallback( (base64: string) => {
onChange(base64);
}, [onChange]);

const handleDrop = useCallback((files: any) => {
const file = files[0];
const reader = new FileReader();

reader.onload = (event: any) => {
setBase64(event.target.result);
handleChange(event.target.result);
}

reader.readAsDataURL(file);
}, [handleChange]);

const { getRootProps, getInputProps } = useDropzone({
maxFiles: 1,
onDrop: handleDrop,
disabled,
accept: {
'image/jpeg': [],
'image/png': []
}
});

return (
<div
{ ...getRootProps({
className: "w-full p-4 text-white text-center border-2 border-dotted rounded-md border-neutral-700"
})}
>
<input {...getInputProps()} />
{
base64 ? (
<div className='flex items-center justify-center'>
<Image
src ={base64}
height = '100'
width = "100"
alt = "Uploaded image"
/>
</div>
) : (
<p className='text-white'>{label}</p>
)
}
</div>
);
}

export default ImageUpload

ModifyEditModal

Modify file components/modals/EditModal.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...
<ImageUpload
value={profileImage}
disabled={isLoading}
onChange={(image)=>setProfileImage(image)}
label="Upload profile image"
/>
<ImageUpload
value={coverImage}
disabled={isLoading}
onChange={(image)=>setCoverImage(image)}
label="Upload cover image"
/>
<Input
placeholder="Name"
onChange={(e)=> setName(e.target.value)}
value={ name }
disabled={isLoading}
/>
...

Demo

Click Edit Button:

Click Save Button:

请我喝杯咖啡吧~

支付宝
微信