Skip to content

Instantly share code, notes, and snippets.

@chadmuro
Created August 5, 2021 10:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chadmuro/e770ade905c27eb76f44559e6c4eb6be to your computer and use it in GitHub Desktop.
Save chadmuro/e770ade905c27eb76f44559e6c4eb6be to your computer and use it in GitHub Desktop.
File Input
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;
@renbesson
Copy link

Straight forward piece of code that works like a charm! Thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment