Skip to content

Commit

Permalink
feat: add useScript and useStylesheet hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
jerelmiller committed Jun 2, 2020
1 parent 5f94ddd commit d24fc97
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/hooks/useScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';

const useScript = (src) => {
const [loaded, setLoaded] = useState(false);

useEffect(() => {
const script = window.document.createElement('script');

script.async = true;
script.crossOrigin = 'anonymous';
script.onload = () => setLoaded(true);
script.src = src;
document.body.appendChild(script);

return () => document.body.removeChild(script);
}, [src]);

return loaded;
};

export default useScript;
21 changes: 21 additions & 0 deletions src/hooks/useStylesheet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';

const useStylesheet = (src) => {
const [loaded, setLoaded] = useState(false);

useEffect(() => {
const link = window.document.createElement('link');

link.rel = 'stylesheet';
link.crossOrigin = 'anonymous';
link.onload = () => setLoaded(true);
link.href = src;
document.head.appendChild(link);

return () => document.head.removeChild(link);
}, [src]);

return loaded;
};

export default useStylesheet;

0 comments on commit d24fc97

Please sign in to comment.