Skip to content

Instantly share code, notes, and snippets.

@ibelick
Created March 15, 2022 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibelick/1abb6732c0540514a113fb8642833123 to your computer and use it in GitHub Desktop.
Save ibelick/1abb6732c0540514a113fb8642833123 to your computer and use it in GitHub Desktop.
Display an image selected from input type file with React + TypeScript
const SelectDisplayImage = () => {
const [image, setImage] = useState<null | string>(null);
const onImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (!input.files?.length) {
return;
}
const file = input.files[0];
setImage(URL.createObjectURL(file));
};
return (
<div>
<input type="file" onChange={onImageChange} className="filetype" />
{image ? <img src={image} alt="preview image" /> : null}
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment