Created
August 5, 2021 10:52
File Input
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 { useState, useEffect } from 'react'; | |
import Button from '@material-ui/core/Button'; | |
import Box from '@material-ui/core/Box'; | |
const FileInput = () => { | |
const [selectedImage, setSelectedImage] = useState(null); | |
const [imageUrl, setImageUrl] = useState(null); | |
useEffect(() => { | |
if (selectedImage) { | |
setImageUrl(URL.createObjectURL(selectedImage)); | |
} | |
}, [selectedImage]); | |
return ( | |
<> | |
<input | |
accept="image/*" | |
type="file" | |
id="select-image" | |
style={{ display: 'none' }} | |
onChange={e => setSelectedImage(e.target.files[0])} | |
/> | |
<label htmlFor="select-image"> | |
<Button variant="contained" color="primary" component="span"> | |
Upload Image | |
</Button> | |
</label> | |
{imageUrl && selectedImage && ( | |
<Box mt={2} textAlign="center"> | |
<div>Image Preview:</div> | |
<img src={imageUrl} alt={selectedImage.name} height="100px" /> | |
</Box> | |
)} | |
</> | |
); | |
}; | |
export default FileInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Straight forward piece of code that works like a charm! Thanks for sharing.