Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add customAttributes option to useScript() hook #267

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Expand Up @@ -228,6 +228,7 @@ declare module "@uidotdev/usehooks" {
src: string,
options?: {
removeOnUnmount?: boolean;
customAttributes?: Record<string, string>;
}
): "unknown" | "loading" | "ready" | "error";

Expand Down
4 changes: 4 additions & 0 deletions index.js
Expand Up @@ -1112,6 +1112,10 @@ export function useScript(src, options = {}) {
script.src = src;
script.async = true;
script.setAttribute("data-status", "loading");
const customAttributes = optionsRef.current?.customAttributes ?? {};
for(const [key, value] in Object.entries(customAttributes)) {
script.setAttribute(key, value);
}
document.body.appendChild(script);

const handleScriptLoad = () => {
Expand Down
5 changes: 4 additions & 1 deletion usehooks.com/src/content/hooks/useScript.mdx
Expand Up @@ -29,7 +29,7 @@ import StaticCodeContainer from "../../components/StaticCodeContainer.astro";
| Name | Type | Description |
| ---------------- | ------ | ----------- |
| src | string | This is the URL source of the script to be loaded. |
| options | object | This is an optional configuration object provided when calling `useScript`. It currently accepts one property `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount. |
| options | object | This is an optional configuration object provided when calling `useScript`. It currently accepts two optional properties: `removeOnUnmount` which when set to `true`, will remove the script tag from the document body on component unmount, and `customAttributes` which is an object of custom string attributes that will be added to the script tag, this can be useful for specifying things like license keys in `data-x` attributes. |
</div>

### Return Values
Expand Down Expand Up @@ -58,6 +58,9 @@ export default function App() {
`https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.js`,
{
removeOnUnmount: false,
customAttributes: {
"data-uid": "useScript",
},
}
);

Expand Down