arrow-left
All pages
gitbookPowered by GitBook
1 of 34

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

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-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.

hashtag
module

hashtag
Syntax

hashtag
Example

import { useDollars } from "@atomico/hooks/use-dollars";
useDollars(ref: Ref<HTMLSlotElement>);

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.

hashtag
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-keyboar

capture key combinations easily

hashtag
Module

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

hashtag
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

hashtag
Example

use-click-coordinates

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

hashtag
Module

hashtag
Syntax

where:

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

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

hashtag
Coordinates

Where :

  • x: MouseEvent.clientX

  • y: MouseEvent.clientY

  • offset.x : MouseEvent.offsetX

  • offset.Y : MouseEvent.offsetY

hashtag
Example

import { useClickCoordinates } from "@atomico/hooks/use-click-coordinates";
useClickCoordinates(ref, handlerClick);
interface Coordinates {
  x: number;
  y: number;
  offset: {
    x: number;
    y: number;
  };
}

use-form

Communicate the component with external forms.

hashtag
Module

hashtag
useForm syntax

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

hashtag
useFormListener syntax

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

hashtag
useFormInputHidden syntax

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

hashtag
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:

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

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

hashtag
Example

import { 
    useForm, 
    useFormListener, 
    useFormInputHidden, 
    useFormInputRadio 
} from "@atomico/hooks/use-form";
const ref = useForm()
useFormListener("reset",handler);
useFormInputHidden("my-field","my-value");
myComponent.props = { name: String, checked: Boolean }
const refInput = useFormInputRadio(<input slot="input" value="my-value"/>);

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

use-css

Inject CSS into the shadowRoot

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

hashtag
Import

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

hashtag
Sintaxis

useCss(cssText: string);

hashtag
Example

hashtag
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-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.

hashtag
Module

hashtag
Syntax

hashtag
Example

import { useCssLightDom } from "@atomico/hooks/use-css-light-dom";
useCssLightDom(sheets: import("atomico").Sheets);
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>
  );
}

use-render

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

hashtag
Modulo

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

hashtag
Syntax

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

hashtag
Example

use-async-effect

Execute useEffect but asynchronously

hashtag
Modulo

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

hashtag
Syntax

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

@atomico/hooks

series of useful hooks for creating webcomponents

Hooks
v3
v4

✅

✅

✅

✅

✅

✅

use-click-coordinates

✅

✅

use-copy

✅

✅

use-css-light-dom

✅

✅

use-ref-values

✅

⚠️

use-current-value

✅

use-slot
use-render
use-child-nodes

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.

hashtag
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-attributes

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

hashtag
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

hashtag
Example

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.

hashtag
useIntersectionObserver

hashtag
useRefIntersectionObserver

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;
    }
`
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-script

load global scripts when mounting the component

hashtag
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-copy

Copies the content in text format of a reference.

hashtag
Module

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

hashtag
Syntax

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

Where:

  1. ref : Node reference to copy

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

hashtag
Example

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.

hashtag
Example

hashtag
Live 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

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

hashtag
module

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

hashtag
Syntax useReflectEvent

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

hashtag
Syntax reflectEvent

Reflects on an element the given event

useReflectEvent(
    refFrom: Ref<Element>,
    refTo: Ref<Element>,
    eventType: string
);
reflectEvent( target: Element, event: Event );

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}.

hashtag
Import

hashtag
Sintaxis

Where:

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

hashtag
Example

use-listener

Associate a listener with a reference

hashtag
Module

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

hashtag
Syntax

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

hashtag
Example

use-debounce-state

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

hashtag
Module

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

hashtag
Syntax

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

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)

hashtag
Example

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

use-slot

Retrieves the nodes assigned to a slot.

timeout: the delay will be the milliseconds for setTimeout
  • idle : the delay will be the milliseconds for requestIdleCallback

  • import { useDisabled } from "@atomico/hooks/use-disabled";
    Element.matchesarrow-up-right

    use-resize-observer

    Observe the size change of a reference.

    hashtag
    Module

    hashtag
    Syntax

    hashtag
    useResizeObserver

    Where:

    • ref: Ref, reference to observe the resizing.

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

    hashtag
    useResizeObserverState

    Where:

    • ref: Ref, reference to observe the resizing.

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

    hashtag
    Example

    use-responsive-state

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

    hashtag
    Module

    hashtag
    Syntax

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

    Where:

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

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

    hashtag
    Expressions

    Where:

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

    • caseState: Status to show if matchMedia match.

      • size: size expression to observe, example:

    hashtag
    Example

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

    use-promise

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

    hashtag
    Module

    hashtag
    Syntax

    Where :

    const disabled:boolean = useDisabled(matches?: string = "fieldset");
    import {
      useResizeObserver,
      useResizeObserverState,
    } from "@atomico/hooks/use-resize-observer";
    import { useResponsiveState } from "@atomico/hooks/use-responsive-state";

    width

  • height

  • x

  • y

  • top

  • right

  • bottom

  • left

  • width

  • height

  • x

  • y

  • top

  • right

  • bottom

  • left

  • DOMRectarrow-up-right
    DOMRectarrow-up-right
  • "1080px": (min-width: 1080px)

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

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

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

  • const state = useResponsiveState`
        phone, tablet 720px, destop 1080px
    `;
  • 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.

  • hashtag
    Example

    use-mutation-observer

    Observe the changes of a reference using MutationObserver

    hashtag
    Module

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

    hashtag
    useMutationObserver syntax

    Observe mutations using a callback

    hashtag
    useMutationObserver syntax

    Reflects mutations in a state

    hashtag
    Example

    hashtag

    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

    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:

    hashtag
    Syntax and example

    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.

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

    hashtag
    Modulo

    useResizeObserver(
      ref,
      (rect) => void
    );
    const rect = useResizeObserverState(ref);
    "<defaultState>, <caseState> <size>"
    import { usePromise } from "@atomico/hooks/use-promise";
    const [result, status] = usePromise(
      asyncFunction,
      runFunction,
      optionalArguments
    );
    useMutationObserver(    
        ref: Ref<Element>,    
        observe: MutationCallback,    
        config?: MutationObserverInit
    );
    circle-info

    All redirected hooks must exist under a slot

    hashtag
    Live example

    <my-component>
        <img slot="slide" src="slide-1"/>
        <img slot="slide" src="slide-1"/>
        <img slot="slide" src="slide-1"/>
    </my-component>
    <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>
    hashtag
    Syntax

    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.

    hashtag
    Example

    This hook is used by @atomico/components/router

    import { useChannel } from "@atomico/hooks/use-channel";
    useContextchevron-right
    const mutations:MutationRecord[] = useMutationObserverState(    
        ref: Ref<Element>,    
        config?: MutationObserverInit
    );

    use-parent

    Retrieve a node higher than the current webcomponent.

    hashtag
    Module

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

    hashtag
    Syntax useParent

    Where:

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

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

    hashtag
    Syntax useParentPath

    Where:

    • parents: parent nodes of the webcomponent

    • composed: bypasses shadow DOM in parent capture.

    hashtag
    Example

    WebComponents.devWebComponents.devchevron-right

    useSlot

    hashtag
    Module

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

    hashtag
    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

    hashtag
    Live example

    use-controller

    Use a ReactiveController.

    hashtag
    Modulo

    hashtag
    Syntax

    Where:

    WebComponents.devWebComponents.devchevron-right
    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>
      );
    }
    const channel = "MyChannel";
    const [parentValue, setChildValue] = useChannel(channel);
    const selector = "form";
    const parent = useParent(selector);
    Logo
    Logo

    AController: ReactiveController, A ReactiveControllerarrow-up-right with property a.

    import { useController } from "@atomico/hooks/use-controller";
    class AController {/*...*/}
    
    const useA = x => useController(host => new AController(host, x));
    const { a } = useA('a');
    Element.matchesarrow-up-right
    WebComponents.devWebComponents.devchevron-right

    use-router

    Hooks to work with routes in the browser

    Hook to handle routes based on expressions according to the library, this hook is used by ****

    hashtag
    Module

    hashtag

    WebComponents.devWebComponents.devchevron-right
    const parents = useParentPath(composed?: boolean);
    Logo
    Logo
    useRouter syntax

    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

    hashtag
    useRoute syntax

    Share the return from useRouter

    hashtag
    useRouteMatch syntax

    https://github.com/uppercod/exp-routearrow-up-right
    @atomico/components/router
    import { 
        useRouter, 
        useRoute, 
        useRouteMatch, 
        useRedirect, 
        redirect, 
        getPath 
    } from "@atomico/hooks/use-router";
    const [ view, path, params, search ] = useRouter({
        "/":()=><h1>home</h1>,
        "user/{id}":({ id })=><my-user id={id}/>,
    })
    const [ view, path, params, search ] = useRoute("/",()=><h1>home</h1>);
    const match = useRouteMatch();
    
    const isHome = match("/home");

    use-child-nodes

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

    hashtag
    Modulo

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

    hashtag
    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.

    hashtag
    Example

    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.

    function component() {
      const [childNodes] = useChildNodes();
      return (
        <host>
          {childNodes
            .filter((node) => node.localName == "h1")
            .map((Title) => (
              <Title onclick={() => console.log("click h1!")} />
            ))}
        </host>
      );
    }
    WebComponents.devWebComponents.devchevron-right
    Basic
    Logo
    WebComponents.devWebComponents.devchevron-right
    Counter
    WebComponents.devWebComponents.devchevron-right
    Logo
    Logo

    use-force-render

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

    triangle-exclamation

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

    hashtag
    Modulo

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

    hashtag
    Syntax

    Where:

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

    hashtag
    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:

    const forceRender = useForceRender();
    function component() {
      const ref = useRef();
      const forceRender = useForceRender();
    
      return (
        <host>
          {ref.current.anyProp}
          <my-component ref={ref} onclick={forceRender}></my-component>
        </host>
      );
    }
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Logo
    WebComponents.devWebComponents.devchevron-right
    Ejemplo en vivo
    Logo
    WebComponents.devWebComponents.devchevron-right
    WebComponents.devWebComponents.devchevron-right
    WebComponents.devWebComponents.devchevron-right
    Logo
    Logo
    Logo