All pages
Powered by GitBook
1 of 34

@atomico/hooks

series of useful hooks for creating webcomponents

Hooks
v3
v4

use-slot

✅

✅

use-render

✅

✅

use-child-nodes

✅

✅

use-click-coordinates

✅

✅

use-copy

✅

✅

use-css-light-dom

✅

✅

use-ref-values

✅

⚠️

use-current-value

✅

useCurrentValue

The useCurrentValue hook allows associating a value with current based on its parameter, equivalent to:

const ref = useRef();

ref.current = value;

With the useCurrentValue hook

useCurrentValue(value)

use-intersection-observer

Create an IntersectionObserver instance to observe the intersection of the webcomponent or a reference.

Remember that to detect any intercept, a minimum height and width of the reference to be observed is required.

useIntersectionObserver

import { useIntersectionObserver } from "@atomico/hooks/use-intersection-observer";

function component(){
    useIntersectionObserver(([entry])=>{
        console.log("",{isIntersecting })
    },{
          threshold: 0.1,
    })
    return <host shadowDom/>
}

component.styles = css`
    :host{
        display: block;
        width: 100%;
        min-height: 1px;
    }
`

useRefIntersectionObserver

import { useHost } from "atomico";
import { useRefIntersectionObserver } from "@atomico/hooks/use-intersection-observer";

function component(){
    const host = useHost();
    useRefIntersectionObserver(
        ref,
        ([entry])=>{
            console.log("",{isIntersecting })
        },{
          threshold: 0.1,
        }
    );
    return <host shadowDom/>
}

component.styles = css`
    :host{
        display: block;
        width: 100%;
        min-height: 1px;
    }
`

use-ref-values

Consume the values of a reference without major inconvenience

This hook has a behavior similar to useEffect but focused on resolving the consumption of one or more references.

Example

import { useRef } from "atomico";
import { useRefValues } from "@atomico/hooks/use-ref-values";

function component(){
    const ref = useRef();
    
    useRefValues(
        // 👇 current will be the value assigned to ref.current
        ([current])=>{
            // 1️⃣ here the effect dependent on the reference
            // 🔴 The following line is optional
            return ()=>{
            // (Optional) here the cleanup of the reference dependent effect
            }
        },
        [ref]
    );
    
    return <host>
        <input ref={ref}/>
    </host>
}

use-script

load global scripts when mounting the component

Syntax

const src = "https://code.jquery.com/jquery-3.6.0.min.js";
const done = ()=> console.log( $ );
const status = useScript(src, done);

where:

  1. src: javascript type resource to inject into document.head

  2. done: optional , callback when called at the end of the script load

  3. status: script load status

use-attributes

capture all attributes that are defined in the webcomponent but are not props

Syntax

const attrs = useAttributes();

Where:

  1. attrs: all the attributes defined on the webcomponent but that are not props, to facilitate reading this hook transforms the index to camelCase

Example

LogoWebComponents.devWebComponents.dev

use-prop-proxy

Share values from the scope via setter and getters

allows to create a setter and getter for a property of the webcomponent, this is useful for:

  1. Reflect elements internal to the scope as part of the instance, example references.

  2. Observe from the scope the mutations external to Atomico.

Example

import { Props, useRef } from "atomico";
import { useRender } from "@atomico/hooks/use-render";
import { usePropProxy } from "@atomico/hooks/use-prop-proxy";

function component(props: Props<typeof component>) {
  const refInput = useRef();

  useRender(() => (
    <input
      slot="input"
      class="reset"
      ref={refInput}
      type={props.type}
      value={props.value}
    />
  ));

  usePropProxy("value", {
    get() {
      return refInput.current?.value;
    },
  });

  return (
    <host shadowDom>
      <slot name="input"></slot>
    </host>
  );
}

component.props = {
  type: String,
  value: String,
};

use-click-press

The useClickPress hook will allow you to execute a callback with acceleration according to the click time, for example in the input type number we have 2 buttons by default, an up arrow and a down arrow, these allow us to modify the input value, either:

  1. Increase the value before a click in a unit.

  2. Increase the value by more than one unit according to the click pressure time.

Example

import { useClickPress } from "@atomico/hooks/use-click-press";

function counter() {
  const refButton = useRef();

  const [value, setValue] = useProp("value");

  const increment = () => setValue((value) => value + 1);

  useClickPress(refButton, increment);

  return (
    <host>
      <h1>value: {value}</h1>
      <button ref={refButton}>Increment</button>
    </host>
  );
}

counter.props = { value: { type: Number, value: 0 } };j

Live example

LogoWebComponents.devWebComponents.dev

use-dollars

Create reactive templates that interact with the state of your webcomponent

The purpose of this hook is to allow communication between the webcomponent and the lightDOM without knowing the DOM, achieving with this hook:

  1. expose the webcomponent's api to the lightDOM and react to it.

  2. data binding between the state of the webcomponent and the lightDOM.

module

import { useDollars } from "@atomico/hooks/use-dollars";

Syntax

useDollars(ref: Ref<HTMLSlotElement>);

Example

LogoWebComponents.devWebComponents.dev

use-reflect-event

the useReflectEvent hook reflects the event from the reference origin to the reference destination

the useReflectEvent hook reflects the event from the reference origin to the reference destination, the captured event will be canceled

One of the possibilities of this hook is to reflect the events inside shadowDOM to lightDOM, example when using forms

module

import { 
    useReflectEvent, 
    reflectEvent  
} from "@atomico/hooks/use-reflect-event";

Syntax useReflectEvent

useReflectEvent(
    refFrom: Ref<Element>,
    refTo: Ref<Element>,
    eventType: string
);

useRefectEvent will listen for the eventType of refFrom, to reflect it on refTo

Syntax reflectEvent

reflectEvent( target: Element, event: Event );

Reflects on an element the given event

use-keyboar

capture key combinations easily

Module

import { useKeyboard } from "@atomico/hooks/use-keyboard";

Syntax

useKeyboard(
    ref: Ref<Element>,
    keysCode: string[],
    callback: (event: KeyboardEvent)=>void
);

where:

  1. ref, the reference to associate the event keydown and keyup.

  2. keysCode: key combination to capture

  3. callback: receives the last event of the key combination

Example

LogoWebComponents.devWebComponents.dev

use-click-coordinates

The usesClickCoordinates hook is for capturing click coordinates, this is useful when positioning a tooptip or creating visual effects

Module

import { useClickCoordinates } from "@atomico/hooks/use-click-coordinates";

Syntax

useClickCoordinates(ref, handlerClick);

where:

  1. ref: node reference to observe the click event.

  2. handlerClick: Callback that receives the coordinates of the click event.

Coordinates

interface Coordinates {
  x: number;
  y: number;
  offset: {
    x: number;
    y: number;
  };
}

Where :

  • x: MouseEvent.clientX

  • y: MouseEvent.clientY

  • offset.x : MouseEvent.offsetX

  • offset.Y : MouseEvent.offsetY

Example

LogoWebComponents.devWebComponents.dev

use-copy

Copies the content in text format of a reference.

Module

import { useCopy } from "@atomico/hooks/use-copy";

Syntax

const copy:()=>void = useCopy(ref);

Where:

  1. ref : Node reference to copy

  2. copy: Callback, executes the content copy event.

Example

LogoWebComponents.devWebComponents.dev

use-debounce-state

creates a bottleneck to the definition of a state, limits concurrency.

Module

import { useDebounceState } from "@atomico/hooks/use-debounce-state";

Syntax

this hook is similar to useState, but the purpose of this hook is to bottleneck the state at update time

const [state, setState] = useDebounceState(
    delay:number, 
    initialState: any,
    mode?: "fps" | "timeout" | "idle"
);

mode differences

  1. fps:

    1. if delay is set to 1, the update is executed for each cycle of requestAnimationFrame(60fps),

    2. if delay is defined as 2, the update is executed for every 2 cycle of requestAnimationFrame(30fps)

  2. timeout: the delay will be the milliseconds for setTimeout

  3. idle : the delay will be the milliseconds for requestIdleCallback

Example

LogoWebComponents.devWebComponents.dev

use-form

Communicate the component with external forms.

Module

import { 
    useForm, 
    useFormListener, 
    useFormInputHidden, 
    useFormInputRadio 
} from "@atomico/hooks/use-form";

useForm syntax

If the webcomponent is nested within a form tag, this hook will return that form tag as a reference.

const ref = useForm()

useFormListener syntax

If the webcomponent is nested within a form tag, you will be able to listen to events from that tag through useFormListener.

useFormListener("reset",handler);

useFormInputHidden syntax

el hook renderiza un input hidden en el lightDOM cuyo name y value del input seran los parametros que el hook resiva

useFormInputHidden("my-field","my-value");

useFormInputRadio

One of the difficult inputs to standardize when working with shadowDOM is the radio input, thanks to this hook you will be able to create and observe a radio input synchronized with the form and its webcomponent.

This hook requires the definition of the properties in its webcomponent:

myComponent.props = { name: String, checked: Boolean }

You can work with the input from the component logic, example:

const refInput = useFormInputRadio(<input slot="input" value="my-value"/>);

return <host>
    <slot name="input"/>
</host>;

Your component will automatically be reactive to the change of the states of the radio input

Example

LogoWebComponents.devWebComponents.dev

use-listener

Associate a listener with a reference

Module

import { useListener } from "@atomico/hooks/use-listener";

Syntax

useListener(
    ref: Ref<Element>, 
    name: string, 
    handler: (event)=>void, 
    option?: boolean | AddEventListenerOptions 
);

Example

LogoWebComponents.devWebComponents.dev

use-disabled

Synchronize the state of the disabled prop with the fieldset tag

Inherit the disabled status of a parent tag type fieldset, under certain rules:

  1. The label must be on the lightDOM.

  2. The component that uses this hook must declare the prop {disabled: Boolean}.

Import

import { useDisabled } from "@atomico/hooks/use-disabled";

Sintaxis

const disabled:boolean = useDisabled(matches?: string = "fieldset");

Where:

  1. matches: Optional string, allows to change the search of the parent tag fieldset for another tag or selector compatible with Element.matches.

Example

LogoWebComponents.devWebComponents.dev

use-css

Inject CSS into the shadowRoot

Inject tag style into shadowRoot with content given as parameter to use CSS.

Import

import { useCss } from "@atomico/hooks/use-css";

Sintaxis

useCss(cssText: string);

Example

LogoWebComponents.devWebComponents.dev

Note

This hook was not created as a replacement for component.styles, it is rather a utility that seeks to facilitate the integration of css from a customHook, either by defining a state or another action.

use-channel

create connection between components to share internal states

Now, Atomico includes a context API as part of its core. We recommend implementing it as an alternative to using useChannel.

useContext

An alternative to React's context but solely based on hooks.

Modulo

import { useChannel } from "@atomico/hooks/use-channel";

Syntax

const channel = "MyChannel";
const [parentValue, setChildValue] = useChannel(channel);

Where :

  1. channel: String, defines the name of the event to be used to generate the channel.

  2. parentValue: Value inherited by the parent component.

  3. setChildValue: Callback, defines a value for nested components.

Example

LogoWebComponents.devWebComponents.dev

This hook is used by @atomico/components/router

use-promise

The usePromise hook consumes an asynchronous function is ideal for using fetch or other asynchronous tasks.

Module

import { usePromise } from "@atomico/hooks/use-promise";

Syntax

const [result, status] = usePromise(
  asyncFunction,
  runFunction,
  optionalArguments
);

Where :

  • result: Retorno de la promesa

  • status: Estado de la promesa:

    • "": Without executing.

    • "pending": In action.

    • "fulfilled": Successfully executed.

    • "rejected": Executed with error.

  • asyncFunction: asynchronous function.

  • runFunction: Booleano, if true it will execute the promise and define the status.

  • optionalArguments: Optional any[], allows to regenerate the promise through arguments.

Example

LogoWebComponents.devWebComponents.dev

use-responsive-state

Declare a state based on a responsive expression similar to using the tag img[srcset].

Module

import { useResponsiveState } from "@atomico/hooks/use-responsive-state";

Syntax

const expression = "phone, tablet 720px, destop 1080px";
const state = useResponsiveState(expression);
const state = useResponsiveState`
    phone, tablet 720px, destop 1080px
`;

Where:

  • state: String, Current state according to the comparison between experiment and matchMedia.

  • expression: String, An expression that declares the serialized states.

Expressions

"<defaultState>, <caseState> <size>"

Where:

  • defaultState: Default state this cannot contain the use of commas ", ".

  • caseState: Status to show if matchMedia match.

    • size: size expression to observe, example:

      • "1080px": (min-width: 1080px)

      • "1080x720px": (min-width: 1080px) and (min-height: 720px)

      • "50rem": (min-width: 50rem)

      • "50em": (min-width: 50em)

Example

The following example shows the use of useResponsiveState, to display a message based on the mediaquery.

LogoWebComponents.devWebComponents.dev

use-parent

Retrieve a node higher than the current webcomponent.

Module

import { useParent, useParentPath } from "@atomico/hooks/use-parent";

Syntax useParent

const selector = "form";
const parent = useParent(selector);

Where:

  • selector: String, Selector to be used by Element.matches when searching for the parent.

  • parent: Element, ascending search result according to selector.

Syntax useParentPath

const parents = useParentPath(composed?: boolean);

Where:

  • parents: parent nodes of the webcomponent

  • composed: bypasses shadow DOM in parent capture.

Example

LogoWebComponents.devWebComponents.dev

use-resize-observer

Observe the size change of a reference.

Module

import {
  useResizeObserver,
  useResizeObserverState,
} from "@atomico/hooks/use-resize-observer";

Syntax

useResizeObserver

useResizeObserver(
  ref,
  (rect) => void
);

Where:

  • ref: Ref, reference to observe the resizing.

  • rect: Object, the return of DOMRectReadOnly.toJSON(), documentation of DOMRect

    • width

    • height

    • x

    • y

    • top

    • right

    • bottom

    • left

useResizeObserverState

const rect = useResizeObserverState(ref);

Where:

  • ref: Ref, reference to observe the resizing.

  • rect: Object, the return of DOMRectReadOnly.toJSON(), documentation of DOMRect

    • width

    • height

    • x

    • y

    • top

    • right

    • bottom

    • left

Example

LogoWebComponents.devWebComponents.dev

use-slot

Retrieves the nodes assigned to a slot.

useSlot

Module

import { useSlot } from "@atomico/hooks/use-slot";

Syntax

const optionalFilter = (element)=> element instanceof MyCustomElement;
const childNodes = useSlot(ref, optionalFilter);

Where:

  1. ref: Reference of the slot to observe.

  2. childNodes: List of nodes assigned to the observed slot.

  3. optionalFilter: allows to filter nodes assign to childNodes

Live example

LogoWebComponents.devWebComponents.dev

useProxySlot

useProxySlot allows you to observe the nodes assigned to a slot and reassign them to another slot dynamically, example:

Input: Suppose we have a component that observe the slot[name="slide"] node

<my-component>
    <img slot="slide" src="slide-1"/>
    <img slot="slide" src="slide-1"/>
    <img slot="slide" src="slide-1"/>
</my-component>

output: thanks to useProxySlot you will be able to modify the assignment of the list nodes without losing the nodes in the process as normally happens with useSlot, example:

<my-component>
    <img slot="slide-1" src="slide-1"/>
    <img slot="slide-2" src="slide-1"/>
    <img slot="slide-3" src="slide-1"/>
</my-component>

Syntax and example

import { useRef } from "atomico";
import { useProxySlot } from "@atomico/hooks/use-slot";

function component() {
  const ref = useRef();
  const children = useProxySlot(ref);

  return (
    <host shadowDom>
      <slot name="slide" ref={ref} />
      {children.map((child, index) => (
        <slot name={(child.slot = "slide-" + index)} />
      ))}
    </host>
  );
}

All redirected hooks must exist under a slot

Live example

LogoWebComponents.devWebComponents.dev
Ejemplo en vivo

use-render

Run a second render before the webcomponent render, ideal for collaborative work between shadowDOM and lightDOM

Modulo

import { useRender } from "@atomico/hooks/use-render";

Syntax

useRender(() => <input type="text" />, optionalArguments);

Example

LogoWebComponents.devWebComponents.dev

use-mutation-observer

Observe the changes of a reference using MutationObserver

Module

import { 
    useMutationObserver, 
    useMutationObserverState 
} from "@atomico/hooks/use-mutation-observer";

useMutationObserver syntax

Observe mutations using a callback

useMutationObserver(    
    ref: Ref<Element>,    
    observe: MutationCallback,    
    config?: MutationObserverInit
);

useMutationObserver syntax

Reflects mutations in a state

const mutations:MutationRecord[] = useMutationObserverState(    
    ref: Ref<Element>,    
    config?: MutationObserverInit
);

Example

LogoWebComponents.devWebComponents.dev

use-css-light-dom

share your style sheets between LightDOM and ShadowDOM

This hook creates a style tag in the lightDOM of the component, in order to insert that directly affect the lightDOM, before using this hook consider:

  1. The css is not isolated as if it occurs in the shadowDOM.

  2. It does not support the use of ::slotted selector.

Module

import { useCssLightDom } from "@atomico/hooks/use-css-light-dom";

Syntax

useCssLightDom(sheets: import("atomico").Sheets);

Example

import { css } from "atomico";
import { useCssLightDom } from "@atomico/hooks/use-css-light-dom";

const sheet = css`
  :host {
    display: block;
    background: black;
    color: white;
    padding: 100px;
    border-radius: 1rem;
  }
  :host(:hover) {
    background: crimson;
  }
`;

function myExample() {
  useCssLightDom(sheet);
  return (
    <host>
      <h1>Hello</h1>
    </host>
  );
}
LogoWebComponents.devWebComponents.dev
Basic
LogoWebComponents.devWebComponents.dev
Counter

use-controller

Use a ReactiveController.

Modulo

import { useController } from "@atomico/hooks/use-controller";

Syntax

class AController {/*...*/}

const useA = x => useController(host => new AController(host, x));
const { a } = useA('a');

Where:

  • AController: ReactiveController, A ReactiveController with property a.

use-router

Hooks to work with routes in the browser

Hook to handle routes based on expressions according to the https://github.com/uppercod/exp-route library, this hook is used by @atomico/components/router****

Module

import { 
    useRouter, 
    useRoute, 
    useRouteMatch, 
    useRedirect, 
    redirect, 
    getPath 
} from "@atomico/hooks/use-router";

useRouter syntax

const [ view, path, params, search ] = useRouter({
    "/":()=><h1>home</h1>,
    "user/{id}":({ id })=><my-user id={id}/>,
})

Where:

  1. view: return of the last function executed according to the route match.

  2. path: string, represents the prop of the last path that consists of the path match.

  3. params: parameters captured according to the path

  4. search: parameters captured from the path

useRoute syntax

const [ view, path, params, search ] = useRoute("/",()=><h1>home</h1>);

Share the return from useRouter

useRouteMatch syntax

const match = useRouteMatch();

const isHome = match("/home");

use-async-effect

Execute useEffect but asynchronously

Modulo

import { useAsyncEffect } from "@atomico/hooks/use-async-effect";

Syntax

useAsyncEffect(async () => {
  await fetch("...");
});

use-child-nodes

Captures all nodes not created by the webcomponent render, ideal for apply slot polyfill in LightDOM.

Modulo

import { useChildNodes } from "@atomico/hooks/use-child-nodes";

Syntax

const [childNodes, update] = useChildNodes();

Where :

  1. childNodes : List of nodes that do not belong to the webcomponent render.

  2. update: Callback that forces a new childNodes scan.

Example

function component() {
  const [childNodes] = useChildNodes();
  return (
    <host>
      {childNodes
        .filter((node) => node.localName == "h1")
        .map((Title) => (
          <Title onclick={() => console.log("click h1!")} />
        ))}
    </host>
  );
}

From the example we can highlight that the webcomponent will use all the children not created by the h1 type and will associate the onclick handler with them.

use-force-render

Allows forcing the rendering of the webcomponent without the need to be tied to a state or property

Since the version of atomico@1.14.* there is the useUpdate hook, with the same functionality but in the core of Atomico.

Modulo

import { useForceRender } from "@atomico/hooks/use-force-render";

Syntax

const forceRender = useForceRender();

Where:

  1. forceRender: Callback to force rendering of the webcomponent.

Example

Sometimes the rendering of the webcomponent does not depend on a state or property of this, to reflect these changes you can use useForceRender to regenerate the DOM, example:

function component() {
  const ref = useRef();
  const forceRender = useForceRender();

  return (
    <host>
      {ref.current.anyProp}
      <my-component ref={ref} onclick={forceRender}></my-component>
    </host>
  );
}