deco-cx / community

Deco community material
MIT License
1 stars 0 forks source link

`useScript` API Reference #11

Closed tlgimenes closed 3 months ago

tlgimenes commented 3 months ago

useScript API Reference

Description

The useScript function is designed to help developers inline scripts into a web page with minimal payload. It receives a function and its arguments as parameters and returns the stringified, minified version of the function. This is particularly useful for inlining event handlers and other scripts directly into HTML, optimizing performance by reducing the amount of JavaScript sent over the network. It integrates seamlessly with the hx-on: handlers of HTMX.

Importing

import { useScript } from "apps/utils/useScript.ts";

Parameters

Return Value

Usage Examples

Example 1: Inline Script with dangerouslySetInnerHTML

In this example, useScript is used to inline a simple script that logs a message when the window loads.

import { useScript } from "apps/utils/useScript.ts";

const onLoad = () => {
  console.log("Window loaded");
};

function ExampleComponent() {
  return (
    <div>
      <h1>Hello, World!</h1>
      <script
        type="module"
        dangerouslySetInnerHTML={{ __html: useScript(onLoad) }}
      />
    </div>
  );
}

export default ExampleComponent;

Example 2: Inline Script with hx-on Attribute

In this example, useScript is used to create a minified event handler for an hx-on:click attribute that changes the text of a button when clicked.

import { useScript } from "apps/utils/useScript.ts";

const onClick = () => {
  event!.currentTarget.innerText = "Clicked!";
};

function ExampleButton() {
  return (
    <button hx-on:click={useScript(onClick)}>
      Click me
    </button>
  );
}

export default ExampleButton;

Notes

tlgimenes commented 3 months ago

https://deco.cx/docs/en/api-reference/use-script