Created
August 3, 2020 17:04
-
-
Save EnetoJara/ca6c908d963777789e91d1ae3250ceb3 to your computer and use it in GitHub Desktop.
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 from "react"; | |
import defaultImage from "./default-profile.jpg"; | |
function If (props) { | |
if (!props.condition) { | |
return <>{ null }</>; | |
} | |
return <>{ props.children }</>; | |
} | |
function ImageUpload () { | |
const [ file, setFile ] = React.useState(null); | |
const [ imagePreviewUrl, setImagePreviewUrl ] = React.useState( | |
defaultImage | |
); | |
const fileInput = React.createRef(); | |
const handleImageChange = (e) => { | |
e.preventDefault(); | |
let reader = new FileReader(); | |
let file = e.target.files[ 0 ]; | |
reader.onloadend = () => { | |
setFile(file); | |
setImagePreviewUrl(reader.result); | |
}; | |
if (file) { | |
reader.readAsDataURL(file); | |
} | |
}; | |
const clickHandler = e => { | |
e.preventDefault(); | |
fileInput.current.click(); | |
}; | |
const handleRemove = () => { | |
setFile(null); | |
setImagePreviewUrl(defaultImage); | |
fileInput.current.value = null; | |
}; | |
return ( | |
<div> | |
<div> | |
<input | |
type="file" | |
ref={ fileInput } | |
onChange={ handleImageChange } | |
/> | |
</div> | |
<div> | |
<img src={ imagePreviewUrl } alt="..." /> | |
</div> | |
<div> | |
<button | |
type="button" | |
color="default" | |
onClick={ clickHandler } | |
> | |
Add Photo | |
</button> | |
<If condition={ file !== null }> | |
<button | |
type="button" | |
onClick={ handleRemove } | |
> | |
remove pic and stuff | |
</button> | |
</If> | |
</div> | |
</div> | |
); | |
} | |
export default ImageUpload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment