Skip to content

Instantly share code, notes, and snippets.

@qnxdev
Last active May 9, 2021 07:13
Show Gist options
  • Save qnxdev/32340e22c5804dfbc8968330b81eb188 to your computer and use it in GitHub Desktop.
Save qnxdev/32340e22c5804dfbc8968330b81eb188 to your computer and use it in GitHub Desktop.
Storing image in localStorage in React
import { useEffect } from "react";
export default function SetImage() {
const saveImage = (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
// convert file to base64 String
const base64String = reader.result
.replace("data:", "")
.replace(/^.+,/, "");
// store file
try{
localStorage.setItem("pic", base64String);
}
catch(e){
console.log(e)
}
document.getElementById(
"display"
).src = `data:image/png;base64,${base64String}`;
};
reader.readAsDataURL(file);
};
useEffect(() => {
if (localStorage) {
const base64String = localStorage.getItem("pic");
document.getElementById(
"display"
).src = `data:image/png;base64,${base64String}`;
}
});
return (
<div>
<input type="file" id="file" onChange={saveImage} />
<img src="" id="display" width="200px" />
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment