Skip to content

Commit

Permalink
useScreenshot hook completed
Browse files Browse the repository at this point in the history
  • Loading branch information
fayeed committed Jul 16, 2020
1 parent e0144be commit 2ea94c2
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 26 deletions.
7 changes: 5 additions & 2 deletions example/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "use-screenshot-hook-example",
"homepage": "https://fayeed.github.io/use-screenshot-hook",
"homepage": "",
"version": "0.0.0",
"license": "MIT",
"private": true,
Expand All @@ -21,5 +21,8 @@
"not dead",
"not ie <= 11",
"not op_mini all"
]
],
"devDependencies": {
"@types/react-dom": "^16.9.8"
}
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
},
"dependencies": {},
"dependencies": {
"html-to-image": "^0.1.1"
},
"peerDependencies": {
"react": "^16.9.0"
},
Expand Down
61 changes: 38 additions & 23 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
import * as React from 'react';

export const useMyHook = () => {
let [{
counter
}, setState] = React.useState<{
counter: number;
}>({
counter: 0
});

React.useEffect(() => {
let interval = window.setInterval(() => {
counter++;
setState({counter})
}, 1000)
return () => {
window.clearInterval(interval);
};
}, []);

return counter;
};
import { useState, useCallback } from "react";
import { toPng, OptionsType, toJpeg } from "html-to-image";
import { UseScreenshotProps, ImgType } from "./types";

export const useScreenshot = (options?: UseScreenshotProps) => {
const { ref } = options || {};
const [image, setImage] = useState<string>();
const [isLoading, setLoading] = useState(false);

const takeScreenshot = useCallback(
async (type?: ImgType, options?: OptionsType) => {
setLoading(true);

try {
let image: string;

const body = document.getElementById("root")!;

if (type === "jpg") {
image = await toJpeg(ref?.current || body, options);
} else {
image = await toPng(ref?.current || body, options);
}

setImage(image);
} catch (e) {
console.error(e);
}

setLoading(false);
},
[]
);

const clear = useCallback(() => setImage(undefined), []);

return { image, takeScreenshot, isLoading, clear };
};
15 changes: 15 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { MutableRefObject } from "react";
import { OptionsType } from "html-to-image";

export type ImgType = "jpg" | "png";

export interface UseScreenshotProps {
ref?: MutableRefObject<any>;
}

export interface UseScreenshotReturnType {
isLoading: boolean;
image: string;
takeScreenshot: (types: ImgType, options: OptionsType) => void;
clear: () => void;
}

0 comments on commit 2ea94c2

Please sign in to comment.