Created
June 22, 2020 10:22
-
-
Save pavinduLakshan/3c63dfceaf3f9bdead9ffb0283f68bce to your computer and use it in GitHub Desktop.
This file contains hidden or 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, { useState, useRef } from 'react'; | |
import axios from 'axios' | |
const ImgUpExample = ({mode,btnText,handleSubmit}) => { | |
const imgUp = useRef(null); | |
const [image, setImage] = useState(); | |
const [imageName, setImageName] = useState(); | |
function handleImage(e) { | |
setImage(e.target.files[0]); | |
setImageName(e.target.files[0].name); | |
} | |
function handleFormSubmit(event) { | |
event.preventDefault(); | |
const data = new FormData(); | |
data.append('file', image); | |
axios.post('/upload-image', data).then(res => { | |
if (res.status === 200) { | |
alert('added'); | |
} | |
}).catch(err => { | |
alert('Error occured.'); | |
console.log(err); | |
}) | |
} | |
return ( | |
<div> | |
<form onSubmit={handleFormSubmit}> | |
<input | |
type="file" | |
style={{ display: 'none' }} | |
ref={imgUp} | |
onChange={handleImage} | |
accept="image/*"></input> | |
<button onClick={e => imgUp.current.click()}>Select photo</button> | |
<button type="submit">Upload Image</button> | |
</form> | |
</div> | |
); | |
}; | |
export default ImgUpExample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment