feat: add loading state for better ux

This commit is contained in:
rutik wankhade 2023-01-26 11:59:11 +05:30
parent 2045e3783a
commit 593e5c1e55

View File

@ -1,4 +1,4 @@
import React, { useContext } from "react"; import React, { useContext, useState } from "react";
// import { exportComponentAsPNG } from "react-component-export-image"; // import { exportComponentAsPNG } from "react-component-export-image";
import "./CoverImage.css"; import "./CoverImage.css";
import { ImgContext } from "../utils/ImgContext"; import { ImgContext } from "../utils/ImgContext";
@ -7,6 +7,8 @@ import domtoimage from "dom-to-image";
const ComponentToImg = (props) => { const ComponentToImg = (props) => {
const [loading, setLoading] = useState(false)
const { unsplashImage } = useContext(ImgContext); const { unsplashImage } = useContext(ImgContext);
const componentRef = React.createRef(); const componentRef = React.createRef();
@ -18,12 +20,15 @@ const ComponentToImg = (props) => {
a.href = data; a.href = data;
a.download = `cover.png`; a.download = `cover.png`;
document.body.appendChild(a); document.body.appendChild(a);
setLoading(false)
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
} }
const downloadImage = async () => { const downloadImage = async () => {
// exportComponentAsPNG(componentRef, 'cover') // exportComponentAsPNG(componentRef, 'cover')
setLoading(true)
const element = componentRef.current; const element = componentRef.current;
@ -57,7 +62,17 @@ const ComponentToImg = (props) => {
<button <button
className="border p-2 bg-gray-700 hover:bg-gray-800 flex items-center text-white text-xl rounded-lg m-4 px-4" className="border p-2 bg-gray-700 hover:bg-gray-800 flex items-center text-white text-xl rounded-lg m-4 px-4"
onClick={() => downloadImage()}> onClick={() => downloadImage()}>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
<span>
{
loading ?
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-white animate animate-spin" fill="currentColor" width="24" height="24" viewBox="0 0 24 24" ><path d="M12 22c5.421 0 10-4.579 10-10h-2c0 4.337-3.663 8-8 8s-8-3.663-8-8c0-4.336 3.663-8 8-8V2C6.579 2 2 6.58 2 12c0 5.421 4.579 10 10 10z"></path></svg>
:
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
}
</span>
<span className="mx-2">Download</span> <span className="mx-2">Download</span>
</button> </button>
</React.Fragment> </React.Fragment>