-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImage.jsx
66 lines (60 loc) · 2.47 KB
/
Image.jsx
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
import { useContext, useRef, useState } from 'react';
import { IsFinalizeContext } from './IsFinalizeContext';
import placeHolderImagePath from './assets/avatar.png';
export default function Image() {
// Check if document is on finalize status
const isFinalize = useContext(IsFinalizeContext);
const [status, setStatus] = useState('save');
const [link, setLink] = useState(placeHolderImagePath);
// Create reference to the file input
const imageUploadRef = useRef();
// Update link everytime the file input value changes
function handleChange() {
const uploadedFile = imageUploadRef.current.files[0];
const cachedURL = URL.createObjectURL(uploadedFile);
setLink(cachedURL);
}
// Toggle between 'edit' and 'save' mode depending on the type of button clicked
function handleClick(e) {
e.preventDefault();
const clickedButton = e.target;
const newStatus = clickedButton.className;
setStatus(newStatus);
}
if (status === 'edit' && !isFinalize) {
// Return a form if status is 'edit'
return (
<div className="image-container">
<img src={link} className="profile-image" />
<form className="image-link">
{/* Hide the original input element and access it via the 'Upload Photo' button */}
<input type="file" onChange={handleChange} id="upload" ref={imageUploadRef} accept="image/png, image/gif, image/jpeg" hidden />
<button
className="photo-uploader"
type="button"
onClick={() => {
document.getElementById('upload').click();
}}
>
Upload Photo
</button>
<button className="save" type="finalize" onClick={handleClick}>
Save
</button>
</form>
</div>
);
} else if (status === 'save' || isFinalize) {
// Return an editable photo container if status is save
return (
<div className="image-container">
<img src={link} className="profile-image" />
{!isFinalize && (
<button className="edit" onClick={handleClick}>
Change Photo
</button>
)}
</div>
);
}
}