Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
working on this documentation...
working on this documentation...
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...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Atomico has been designed to be simple even in complex situations, in this guide you will know some patterns that Atomico offers to create webcomponents at an advanced level.
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...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Creating sites with Atomico is really easy and SEO friendly because:
With Atomico you can perform SSR and SSG thanks to tools like Astro build, with Astro + Atomico you can send previously rendered components to the client, thus giving a result at the HTML level that is really friendly with search engines.
Atomico being really small (3kB) your sites will load fast, especially if you only apply SSG with Atomico.
Atomico not only supports SSR through Astro, you can SSR today with Atomico in Next.js, Express or any environment that supports ESM modules.
(Coming soon) Yes, with Atomico soon you will be able to create blocks for Gutenberg easily
We recommend the use of Astro build with the @atomico/astro plugin, with this you can create sites like atomicojs.dev
Preferably we recommend Astro + React + Atomico, but in case your project inherits the use of Next.js you can do SSR with Atomico in Next.js using @atomico/react.
This guide will know the essentials to start developing webcomponents with Atomico
Thanks for being here and getting started with Atomico. Let's talk a little about what Atomico offers today:
Development agility, Atomico's functional approach simplifies code at all stages of development.
Lightweight inside and out, Atomico allows you to create a component with less code and with a low dependency impact. Approximately 3kb.
Really fast, Atomico has a good performance in the browser and an agile development experience. Let's understand what a webcomponent created with Atomico looks like:
Let's analyze the code in parts ...
What have we imported?
c
: Function that transforms the functional component into a standard customElement.
html
: Function to declare the template of our component, you can also use JSX.
css
: Function that allows creating the CSSStyleSheet (CSS) for our component as long as it declares the shadowDom.
Our component function receives all the props (Properties and Attributes) declared in component.props, the component function declares all the logic and template of the webcomponent. An important rule within Atomico is "every component created with Atomico must always return the tag".
Atomico detects the prop (Properties and Attributes) of the component thanks to the association of the props object, this through the use of index and value allows you to define:
index: Name of the property and attribute.
value: type of the prop.
From the example we can infer that Atomico will create in our webcomponent a property and attribute called message
and this can only receive values of the String
type.
Atomico detects the static styles of your component thanks to the association of the styles
property:
styles accepts individual or list CSSStyleSheet (CSS) values, the return from the css function is a standard CSSStyleSheet, so it can be shared outside of Atomico.
To create our standard customElement we will have to deliver our functional component to the c function of the Atomico module, the c
function will generate as a return a customElement that can be defined or extended.
A micro library inspired by React Hooks, designed and optimized for the creation of webcomponents.
Atomico simplifies learning, workflow and maintenance when creating webcomponents and achieves it with:
Scalable and reusable interfaces: with Atomico the code is simpler and you can apply practices that facilitate the reuse of your code.
Open communication: with Atomico you can communicate states by events, properties or methods.
Agnostic: your custom Element will work in any web-compatible library, eg React, Vue, Svelte or Angular.
Performance: Atomico has a comparative performance at Svelte levels, winning the third position in performance according to webcomponents.dev in a comparison of 55 libraries among which is React, Vue, Stencil and Lit.
With Atomico you can do this and more
Today Atomico is used in the development of design systems for various industries such as Banking, Pledge Systems, Insurance, Clinical, Government and more.
Many teams decide to use Atomico for the development of their design systems thanks to its similarity with React, which greatly facilitates the incorporation of human talent into the development of design systems.
Atomico offers you Storybook 7 Support with superpowers, thanks to @atomico/storybook you can create stories without the need to declare the argTypes or args since @Atomico/storybook creates them for you
@atomico/vite makes it easy for you to build in NPM-friendly ESM format
@atomico/exports makes it easy for you to export your code by automatically adding the metadata so that it is optimally consumed as a package, @atomico/exports
can even automatically create wrappers for React, Preact and Vue
@atomico/potscss-tokens makes it easy for you to maintain a token system efficiently and sustainably
We thank IBM IX since they have shared their experience in the development of the design system for their client Barmer, you can follow this case through Discord or Github.
The props in Atomico are the way to associate the webcomponent properties and reactive attributes that trigger the logic or interface of the webcomponent.
Props is the Atomico recommended way to declare visible and accessible states at the instance level of your webcomponents, with props you can:
Access state via instance, example: document.querySelector("my-component").myStateProp
.
Dispatch events on prop value change, example: document.querySelector("my-component").addEventListener("myPropChange",console.log)
.
Reflect attributes as prop, example: <my-component my-prop="....">
to document.querySelector("my-component").myProp
.
define strict input types for props.
Any function that represents the webcomponent will be able to associate the static object props for the declaration of reactive properties and attributes, for example:
The prop names in Camel Case format will be translated to for use as an attribute to the Kebab Case format, this behavior can be modified through the "attr" property when using a structured declaration.
Structured declarations require the "type" property minimally.
Not all types can use the "reflect" properties.
The declaration of the "value" property can vary depending on the type.
Simple statements allow setting just type validations.
Improve the definition by adding utility declarations, allowing for example to reflect the property's value as attributes, automatically emit events or associate default values. Remember these types of declarations minimally require the use of the type property.
If the "reflect" property is set to true, its value is reflected as an attribute of the webcomponent, this is useful for the declaration of CSS states, example:
It allows dispatching an automatic event before the prop value change, example:
Where:
event.type
: String - optional, name of the event to be emitted when the prop is changed
event.bubbles
: Boolean - optional, indicates that the event can be listened to by containers.
event.detail
: Any - optional, allows to attach a custom detail for the event
event.cancelable
: Boolean - optional, indicates that the event can be canceled by any listener
event.composed
: Boolean - optional, allows the event to exceed the shadow-root limit
Atomico allows the definition of default values of the props.
The association of callback as value allows generating unique values for each instance of the webcomponent, this is useful with the Object and Array types since it eliminates the references between instances.
Atomico removes the use of "this" given its functional approach, but adds the hook [useProp] (hooks / useprop.md) which allows to reference a prop for use with a functional syntax, eg:
Hi, I'm Atomico js and I bring you the React syntax for webcomponents, I think you and I get along very well 😊.
First let's say that Atomico is light since it has a size close to 3kB vs React + ReactDOM that have a size close to 60kB, now if your project is already written in React I can integrate Atomico progressively since a component created can be instantiated as a component for React thanks to , example:
Magical , isn't it?... well now let's speed up your Atomico learning path:
Atomico, like React, allows a declaration of components using only functions, example:
From the example we will highlight the following differences:
In Atomico you only use one import.
useProp
is like useState
, but with the difference that useProp references the state from the webcomponent property defined in counter.props
.
counter.props
allows us to create the properties of our webcomponent, these are like React's propTypes, but with a big difference they are associated with the instance and can be read and modified by referencing the node, example document.querySelector("my-counter").count = 10;
ReactDom.render
needs a reference to mount the component, in Atomico you only need to create the my-counter
tag to create a new instance of the component.
The <host/>
tag is similar to <> </>
for React, but <host/>
represents the webcomponent instance and every component created with Atomico must return the host tag
This is only readability, but in Atomico by convention we do not use capital letters when naming our component, these are only used when creating the customElement as in line 16, since Counter
is instantiable.
Now I want to invite you to learn how to declare a style using Atomico.
It is common to see the use of libraries such as Emotion or styled-components to encapsulate styles in React, but these add an additional cost, be it for performance or bundle, in Atomico there is no such cost.
It is normal for React to create components that you then instantiate within other components, for example:
with Atomico there are certain differences:
The constructor in Atomic is the product of the c function and is the one you will use to register your webcomponent, example:
According to the previous example, you can instantiate MyComponent as a JSX Component, example:
This instance type allows autocompletion at the JSX level and type validation at the Typescript level.
This will be useful for reusing templates, but always remember stateless.
By default, the render is configured to be used within the webcomponent by reading the return of the function, but it can be used outside of Atomico, example:
Render rule "The first node of the render must always be the host tag".
This technique allows you to use any registered custom element without the need to know its tag-name
for its use, example:
Advantage :
Remove leverage from tag-name
Infer the types of the props and autocomplete only if you use JSX and Atomico.
Atomico allows the use of the DOM, for this it establishes its created or recovered node as a constructor, example:
Atomico associates the variable associated with the instance as a constructor, example:
allows to declare a node within the scope of the function as static, this will optimize the diff process between render, achieving better performance in cases of high stress of the UI, example:
the biggest advantage of this is that the node accesses the scope of the webcomponent
Allows to clone a node from the virtualDOM, example:
The objective of this feature is to retrieve slot and use it as a template from the webcomponent.
Atomico allows reusing existing DOM in the document. This is done during the webcomponent instatiation, by setting a special property in the tag to mark it for hydration.
This can be done for shadowDom too:
Atomic creates a customElement from a function, Atomico will take the name of the function and associate it as the name of the CustomElement in CamelCase format, example:
This results in the class name being equal to Button. This feature is useful for tools like Storybook, when serializing the JSX.
Hook that creates a reference that curren is the instance of the webcomponent.
Returns the instance of the webcomponent in reference format, this reference allows to extend behaviors when creating customHooks.
From the example we can highlight that useListener is a customHook that allows listening to an event from the webcomponent without the need to link said event to the VirtualDOM.
The special properties of the event are the well-known Event Init
, you can know more details in the .
These code samples are not part of the standard yet, so polyfills must be used to ensure that it works in all browsers. Read more about Google Chrome's proposal here .
String
✔️
Number
✔️
Boolean
✔️
Object
✔️
Array
✔️
Promise
❌
Symbol
❌
Function
❌
All references to existing types in the browser(HTMLElement, Element, Node, Date, File... more than 300 😎)
❌
shadowDom
Boolean
Enables the use of the shadowDOM on the node.
staticNode
Boolean
Render the node only once, this optimizes the update process as the node is ignored between updates.
cloneNode
Boolean
clone a node of type Element
$<name>
any
the $ prefix allows defining as an attribute in all cases.
Reactivity in the scope of the webcomponent without the use of context(this)
useProp allows you to work with a prop(property) of the webcomponent in a similar way to useState.
Where :
value: Current value of the prop.
setValue: Callback to update the value of the prop.
myProp: string, defines the name of the prop to be used by the hook.
Where:
useCounter is a customHook and that it can work with any property of the webcomponent of type Number.
useCounter returns 2 methods increment and decrement that modify the value of the prop.
useCounter can be instantiated multiple times for different properties.
Allows to run side effects after rendering
Where :
effectCallback
: Function that is executed one or more times according to optionalArgumentList
,effectCallback
can return a function that will be executed only if effectCallback
is executed again or the webcomponent is unmounted.
optionalArgumentList
: Array of arguments that controls the execution of effectCallback
, if an argument ofoptionalArgumentList
changes it will trigger that effectCallback
is executed again without first cleaning the effects subscribed by the previous execution.
useLayoutEffect replicates the logic of useEffect but with synchronous execution after rendering.
useLayoutEffect replicates the logic of useEffect but with synchronous execution before rendering.
Easily observe asynchronous processes
The purpose of this hook is to facilitate the consumption of promises.
where:
callback
: asynchronous function.
args
: arguments that callback requires.
autorun
: by default true, it automatically executes the promise, if it is false the execution of the promise is suspended.
promise
: return object, at the type level it defines the following properties:
pending
: boolean, defines if the promise is executed but pending resolution.
fulfilled
: boolean, defines if the promise has been fulfilled
result
: result of the promise.
rejected
: boolean, defines if the promise has been rejected.
Note: When using Typescript Do not force the types for the second argument of usePromise, as usePromise will infer them from your callback.
It is preferable to use ternary or if to condition the reading of states, since this will help the definition of result
Note: At the type level, autocompletion is conditional on the state you are looking to observe.
Improves the experience of reusing logic between webcomponents based on Atomico
Atomico today offers more Hooks external to the core, we invite you to visit @atomico/hooks with more than 50 hooks to enhance the use of webcomponents 😎
Allows the host that instantiates this useProvider to become the context.
suspend the execution of a render until the resolution of an asynchronous process
with a similar approach to React's use hook, but with scope approach.
scope approach? yes, this hook seeks to resolve a promise from a callback return, this allows you to regenerate the promise according to the scope, example:
where:
getUser
: async callback.
[ userId ]
: arguments that if changed regenerate the promise.
user
: promise return
Like useEffect, the promise will be executed every time the arguments to the second parameter of useAsync change.
Rendering will be suspended until the promise is resolved or rejected, the resolution of the promises can be observed with useSuspense
allows to listen to all useAsync executions nested in the component, example:
Atomico now introduces a new hook called useAbortController, which allows aborting the execution of asynchronous calls, example:
The idea is to create an instance of AbortController every time the hook's parameters change. Each parameter change will abort the previously generated controller, thus cancelling any subscribed promises.
The significant advantage of using useAbortController is the automatic cancellation of asynchronous processes that depend on it when modifying the arguments provided to useAbortController (similar to useEffect).
We recommend the tool, if your project was created with the command npm init @atomico
the test environment will be preconfigured, you can see this pre-configuration at .
To scale the test environment you can complement with tools such as:
: allows you to automate interactions and evaluate interactions of your interface.
: Allows you to evaluate the appearance changes of your component or application between versions.
It is not recommended to use the props API to create an event, as this callback associated as props will have the following limitations:
Its name cannot have the on
prefix since, if it does, Atomico will recognize it as a property expecting to listen to the event.
It can only have one listener, limiting others from observing the event.
Using the hook to dispatch component-level events or any custom hook.
Using the API to dispatch events when the observed prop changes.
Always prefer the two previously mentioned methods, as they allow you to:
Define if the event bubbles.
Define if the event is cancelable.
Define if the bubbling event can penetrate the shadow DOM.
Define a custom constructor for the event.
Having multiple listeners for the event
Cuando se busca comunicar parametros o leer el retorno de este, ejemplo:
Since version Atomico@1.62.0 has introduced a context api as part of the core.
With the new contexts API you will be able to easily communicate components without the need to handle events, by default the communication is top down, but through it you can share anything as long as it is defined as an object.
Atomico's api is similar to React's Context api, let's explore the behavior of Atomico's context api:
create a custom Element as a context, this will serve to synchronize all the components nested within it, you must always remember to declare the tagname of this customElement, example
It allows to consume the return of createContext, let's go back to the previous example and suppose that we want to consume the customElement Theme created by createContext, the code for this would be the following:
In this way useContext captures the value of the parent component or reuses the value given by default to createContext.
By setting the value
prop on the context, you can pass custom values down the sub-tree:
It is highly recommended to always use custom properties to expose the appearance configuration of your component at the static CSS level, since useContext is designed to share information between components in a unidirectional way.
It is ideal to always prioritize a conversation between parent and child through events or props api, but sometimes the depth of the DOM makes this process difficult, for this the context api has been introduced. To remove DOM depth limitations and ensure synchronization based on a unique identifier, some ideal cases to solve with the context api are:
Synchronize states or private methods between components.
Share a value or states inherited from the parent regardless of DOM depth.
function that allows to keep the render on a single node for each execution of it
, the container will be unmounted at the end of each execution of it
.
This allows each fixture execution inside it
to be related to the container used for the test, allowing you to fily test external DOM changes, example:
Build test to custom hooks created with Atomico with an isolated instance and predictable
The "atomico/test-hooks" submodule is a direct part of Atomico's core and will allow you to run the customHook in a controlled way without the need for webcomponents.
function that creates an isolated context that is shared globally with Atomico hooks when executing the load method
Where:
optionalRender: Callback that allows restarting the hook's life cycle, this callback will be executed every time a hook like or requests the scope update, Atomico uses it to render the webcomponent again.
opcionalHost: allows to share an object for the hook , Atomico uses it to share the instance of the webcomponent.
Where:
load: Function that allows to load the hooks to the temporary global context of Atomico.
clearEffect: Function that activates the collector of useLayoutEffect, when executing clear Effect a callback will be returned that allows ending the collector for useEffect, closing the cycle of secondary effects.
If clear Effect receives true as parameter, it communicates the unmounted.
./use-counter.js: customHook to test.
Atomico optimizes the execution of your script by minimizing resources through the rendering control.
Atomico's render cycle works like this:
First, when the component is instantiated, 3 promises will be created pending resolution:
componentInstance.mounted
: resolved once the connectedCallback
has been executed by the customElement.
componentInstance.updated
: the render cycle for first mount or update is encapsulated in componentInstance.updated
.
componentInstance.unmounted
: resolved once the disconnectedCallback
has been executed by the customElement.
Render or rerender cases are:
First render.
Updating a property or attribute.
Update dispatched by a hook
Remember all updates are stacked into a single big loop of componentInstance.updated.
This improves the testing experience since to observe the changes you only have to wait for the resolution of componentInstance.updated
, example:
The first rendering as the update of a prop will call to execute again the function that defines our component, Atomico internally stores the references to support the Hooks api and will render the virtualDOM returned by said function, this is encapsulated within componentInstance.updated
Atomico allows modifying its life cycle in cases of SSR, improving the rendering of the CSS in case of SSR and avoiding the effects of useEffect and useLayoutEffect
Technique to reuse the DOM generated by the SSR, Atomico only in the first render of the component that declares date-hydrate
will retrieve the existing DOM in the DOM not created by Atomico to relate it to the virtualDOM, avoiding creating the node again.
Atomico by default has a good performance, but it can be further optimized if certain techniques are applied.
A static node is equivalent to using node.cloneNode(true)
The renderOnce property renders the node only once, one of the advantages of this technique is that the virtualDOM can access the scope of the function.
./use-counter.test.js: The example is based on the test environment from .
Yes, but Atomico doesn't only depend on ESM, it also depends on the following api's that you will have to cover with Polyfill or some bundle tool.
ESM modules: documentation - caniuse
CustomElements: documentation - caniuse
ShadowRoot: documentation - caniuse
Map: documentation - caniuse
Symbol and Symbol.for: documentation - caniuse
append and prepend: documentation - caniuse
Declarative Shadow DOM: Only for using SSR with webcomponents that use shadowDOM. documentation
Let's understand that today Atomico covers 94% of existing browsers without the need for polyfills or packers, the 6% not covered are usually browsers like ie11 or others.
If you depend on the uncovered segment of browsers you can use the following tools to support the apis necessary for Atomico to work.
polyfill-fastly.io to associate Map, Symbol, append and prepend.
https://github.com/Rich-Harris/shimport to associate esm.
https://github.com/ungap/custom-elements to associate customElements apis.
Atomico with Typescript will improve the scalability of your project thanks to a really productive type system when creating, distributing and maintaining webcomponents
With Atomico and Typescript you will be able to:
📌 If you are a Typescript user I recommend using TSX vs the template-string, as you will benefit from:
JSX runtime, Typescript will automatically import Atomico upon detecting the use of TSX.
Autocompletion and validation of attributes, properties and events of tags and webcomponents.
Webcomponent instance validation using constructors.
Your component as a function does not infer the props, to help infer the props you should use the Props type, example:
From an object: Construct props directly from the declaring object.
From the component: Build the props from the component, internally Atomico captures the property component.props
.
From another customElement component: It's unusal, but when you extend another component you can infer the props from its constructor.
Typescript checks the structure of your component by using the c
function on it, thus validating which props and styles have been attached.
The return of c
is a CustomElement with the types of the associated props, example:
It will report an error to Typescript since this component's props define that value is of type number
, this validation also applies when instantiating your CustromElement in JSX or TSX.
Both TSX or JSX will help you to build better applications since it verifies the types according to the definition of its component, this verification is Free, it does not need plugins, only a tsconfig.json
file and Typescript
to automate the revision.
Working on this documentation...
Simple but useful
If you are a React user, it is common for you to make component declarations like these:
Thanks to the previous code in React we can:
Instantiate your component through its function, example <MyComponent>
Friendly export component as module
In Atomico there are some small differences 👇
Export the return of the c function, since it is instantiable at the JSX level or when using the new operator, example:
Instance with operator new: The new operator allows the instance to associate at the TS level the types declared using Atomico
Instance with document.createElement
Gracias a lo anterior podemos:
Instantiate your component with TS-level type validation either by using JSX or the new operator with, but remember that to get this type of instances you must first have registered your customElement in the same file or another.
Export the useful component to instantiate.
Prefer this export format because tools like @atomico/exports take advantage of this format to automatically create wrappers for React, Preact, and Vue.
Atomico supports through the use of the Host type, the declaration of events and methods, this is useful for associating meta-types to the customElement instance when using JSX or TSX.
Host will be useful for you to declare your event using JSX or TSX regardless of its origin, example:
The use of Host allows that when using JSX or TSX your event is validated through Typescript, this also applies when using @atomico/react, example:
Note event.currentTarget accesses the CustomElement, example properties and more.
That has another benefit, capturing the event as a type to be used in an external handler, example:
Although the props today offer strict rules, Type allows them to be complemented with a direct definition of the types to accept, example:
The above is equivalent to using value as a function, example:
This is also valid for the null type that in Atomic translates as Any, example:
By creating a UI solution that coexists in the web ecosystem such as HTML, libraries and frameworks, since the shadowDOM allows you to:
Protect your UI from libraries like React, Vue and others
Associate styles natively, efficiently and safely
Reference lightDOM content in the shadowDOM
Webcomponents with Shadow DOM are ideal for creating cross UI solutions as they coexist without conflict with the entire web ecosystem.
To protect our component at the DOM manipulation level and take advantage of some of the benefits of the shadowDOM such as:
Slot management
CSS appearance of web component.
The shadowDOM is ideal for creating components that interact with libraries like React, Vue or others. The ShadowDOM protects the DOM it contains from manipulations generated by other libraries.
Slots allow us to reflect existing nodes in the lightDOM into the shadowDOM, example:
This is really useful, since we can group slots according to their name in a specific place of the webcomponent.
We invite you to learn more about slots through the following guide:
The shadowDOM allows you to do something fantastic, protect your CSS from global styles, this has 2 great advantages:
The appearance of our component will not be affected by global CSS declarations.
Customization protected by CSS custom Properties
We invite you to learn more about handling styles in atomic through the following guide:
Atomico integrates very easily into React, either using @atomico/exports or @atomico/react.
CLI that decorates the package.json according to the code to be exported in order to share your code optimally. By using the --wrappers flag the CLI will detect the export of webcomponents and automatically create a wrapper for React, Preact and Vue.
You can learn more about @atomico/exports in the following guide:
With this package you will be able to create wrappers for your Webcomponents in React, even managing to make SSR of your webcomponents in environments like Next.js with these wrappers.
You can learn more about @atomico/react in the following guide:
The Props type allows you to infer the types of props already declared in the props object, example:
The main difference with the Component type is that Props does not generate stricture rules for the component, it only infers the props object to be used as an argument.
At the Typescript Props level, it does evaluate the structure of the component, in order to correctly infer the props, so if the component has a writing error, a warning about this type will be displayed.
Atomico escapes React DOM immutability logic and moves closer to the native DOM API, this means that Atomico at the scope level is only responsible for receiving the props and rendering the DOM, but it does not observe the internal mutations of the DOM automatically, this is because the native level mutations can come from anywhere, for example other libraries. Now for ensure state synchronization it is convenient that every webcomponent that wants to be observed has the obligation to dispatch a change event
You can easily achieve this by using or , applying that you can:
capture change as event
Force a fixed value
the update
function forces an update on the component, in order to redefine value according to the scope
Atomico inherits part of the React syntax and applies it to webcomponents, with a closer to standard approach.
Atomico will not limit your React learning curve, what you learned in Atomico is applicable in React, for example hooks and virtualDOM.
Atomico is 3kB in size which is 7% of React + React-dom.
Better component abstraction, for example the use of the ShadowDOM will avoid the need to use css-in-js like styles-components or emotion, reducing dependencies.
Agnostic Components, what you create with React only works within React, what you create with Atomico works on the web, so you can use your components within React, Vue, Svelte or Html.
Exclusive component for React, the CLI @ atomico / exports automatically generates a wrapper component of your webcomponent for React, improving backward compatibility with React.
The following examples show some differences between React and Atomico.
From the example we will highlight the following differences:
In Atomico you only use one import.
useProp
is like useState
, but with the difference that useProp references the state from the webcomponent property defined in counter.props
.
counter.props
allows us to create the properties of our webcomponent, these are like React's propTypes, but with a big difference they are associated with the instance and can be read and modified by referencing the node, example document.querySelector("my-counter").count = 10;
ReactDom.render
needs a reference to mount the component, in Atomico you only need to create the my-counter
tag to create a new instance of the component.
The <host/>
tag is similar to <> </>
for React, but <host/>
represents the webcomponent instance and every component created with Atomico must return the host tag
This is only readability, but in Atomico by convention we do not use capital letters when naming our component, these are only used when creating the customElement as in line 16, since Counter
is instantiable.
From the example we will highlight the following differences:
The hook api is the same.
the component in Atomico returns the `<host/>
tag.
In Atomico you will have the most useful React hooks such as:
useRef
useState
useReducer
useLayoutEffect
useEffect
useMemo
useCallback
It is common to see the use of libraries such as Emotion or styled-components to encapsulate styles in React, but these add an additional cost, be it for performance or bundle, in Atomico there is no such cost.
Improve the interaction of your inputs with forms using hybrid rendering (LightDOM and ShadowDOM)
Normally we create webcomponents that only work with lightDOM or shadowDOM, example:
With atomico you can go further thanks to the hook which allows you to execute renders independent of the main one, example:
Encapsulate DOM fragments within custom Hooks and then render to any webcomponent.
patch the limitations of webcomponents that use shadowDOM, to improve communication with forms.
With the useRender(...)
fragment we are managing to render an input in the lightDOM, thanks to this we will be able to control said input from inside the webcomponent.
Thanks to useRender you will be able to work together with LightDOM and shadowDOM from the scope of the webcomponent created with Atomico.
By default most hooks infer types automatically, however here are some typing tips:
useState infers the type according to its initial state, if you don't define that state you can define the type manually, example:
The above statement will define that:
message
is of type string
.
setMessage
only accepts values of type string
or functions that return a string
.
useProp will not infer the type from the prop, you must define it, example:
Let's remember that useProp has a return api similar to useState, so the previous declaration will define that:
message
is of type string
.
setMessage
only accepts values of type string
or functions that return a string
.
both useMemo vs useCallback infer its type based on the callback that builds the memo state, but for certain conditions you may need to force the type return, example:
Although useMemo infers that its type is string, you can change the return rules via the first type parameter.
The above statement will define that:
message
is of type string
.
This applies equally to useCallback.
useEvent allows defining the detail structure through the type parameter, example:
The above statement will define that:
The dispatch callback expects an object of type {id: string}
as a parameter.
useRef allows to define through the type parameter the expected value of current in the reference.
The above statement defines:
refForm?.current
is of the type HTMLFormElement
.
useHost defines that current always exists, so the optional selector is not necessary, the type parameter of useHost allows to define the source Element, example:
All hooks in Atomico have Type declarations, explore them when importing each hook as a documentation source.
useContext : Not supported, event api is better practice than context when using webcomponents, example ****
The following error is the most common when using Atomico in Storybook with React.
We recommend using @atomico/react, this package creates a friendly wrapper for React.
Using @atomico/react requires the following script to be imported into the .storybook/preview.js file
Improve the interaction with the forms and accessibility of your components.
It is normal that we use the technique of dispatching events from the component to communicate states and more, but when using forms this changes since the events inside the shadowDOM do not interact with the form outside of it, example:
To solve this we will have to nest an input tag in the lightDOM of our component, in order to reflect the logic of this to the form. Atomico facilitates this hybrid interaction between lightDOM and shadowDOM with the @atomico/hooks/use-render hook that allows executing a second render that works from the lightDOM, example:
With this you have gained full control over the existing input tag in the lightDOM, allowing you to apply styles using the ::slotted
selector, example:
We have created an input tag that allows you to interact directly with the form, this technique is applicable with all the tags that interact with the form, such as button, input, textarea and others.
First thanks for using Atomico 😉, in this guide you will find some useful tips when developing with Atomico, all with the aim that your webcomponents are sustainable and scalable over time.
I will show you a series of useful techniques to start programming your design systems with Atomico, analyzing the recommended structure and its files.
We will analyze the above.
File that imports, exports and declares all the components of our design system, example:
the utilities of this are to centralize everything in components.js are:
Clarity of the definition of customElements in a single file for our entire design system
Export of all customElements to be extended or redefined.
File that centralizes the custom-properties of our design system, example:
From the example above I highlight the custom property declaration pattern
--background
will be a token that can be modified at the instance level and this inherits a global token from our system called --my-ds-input--background
, I want you to notice that the global name of our custom property has a pattern, example:
Where:
prefix: Prefix of our global design system
namespace: group independent of our design system
property: property associated with the system, such as color, size, or other value.
Why use the recommended pattern? To individualize the configuration at the group level and separate the property definition from it thanks to the use of double hyphens (--), internally everything is simplified since the tokens only capture the global configuration global to reflect it to a simpler variable accessible only from the component instance level.
It is the instance of the component either in HTML or JS, example:
From the previous code I highlight:
import of "../tokens"
and the destructuring of the module that declares the use of tokensColor
and tokensInput
.
button.styles: Atomico allows to associate multiple styles through the use of an array.
Button export.
Slots are a powerful feature when working with webcomponents that use the shadowDOM. And thanks to the hook @atomico/hooks/use-slot
you will be able to observe the state of the slot and know the childNodes of this to manage the logic of the template. For example:
Thus managing to easily condition parts of our template to define the slots.
Another trick that useSlot allows us is the interaction at the DOM level, example:
We can even apply filters per instance for a better identification of the node, example:
⚠️ In case of high ui computation use prefer to use slot modifiers inside a useEffect
.
Slots are not only limited to a static definition, you can use them to identify a node and use it to create new nodes according to the logic of the webcomponent, example:
Thanks to useSlot(refSlotTemplateUser)
we get the first node of the Template
slot to be used in the iteration of the results obtained by fetch, with this we have eliminated the leverage of the webcomponent in charge of rendering the user at the level of our webcomponent userFetch
Example
⚠️ the cloneNode
property is available from version atomico@1.37.0
The following format is friendly when sharing a webcomponent to NPM using @atomico/exports
From the previous structure we highlight:
src/define
: import the components from src/elements
and declare them as customElements
src/elements
: groups and export components as CustomElements
since it improves the customElements definition experience, example:
Thanks to @atomico/exports this is really easy, example:
You can see a use case of this structure in @atomico/components
The use of slots improves the composition allowing to reflect the content exposed in the lightDOM
of the component in the shadowDOM
of this, example:
The use of slot is thanks to the use of the ShadowDOM api, to make use of the shadowDom you must declare it as a property of the host tag, example:
<host shadowDom>
I exist inside the shadowDOM</host>
The slotted
selector allows the manipulation of the content exposed as a lightDOM
slot from the shadowDOM
, example:
With Atomico you can define a default slot for your components, this is useful if you want to maintain some compositional consistency without the need to declare the use of slot, example:
To define a default slot, you only have to declare slot
in the props, example:
Consider this practical only if the composition is leveraged to the container, this does not prevent you from modifying the slot property from the component instance.
Atomico has the hook @atomico/hooks/use-slot that appends the slotchange event to a reference, this will allow you to hide slots if they do not declare content, example:
Implement SSR and SST without friction
Atomico and automatic SSR support, you will not need additional packages, example:
For this case we are using a JS-only component to avoid compilation in the example. you can achieve the same with JSX or TSX.
You will not need any additional package, atomic internally understands that the component must be hydrated
Unlike other libraries, Atomico automatically hydrates when mounting the component in the DOM, so no additional client configuration is required.
To use SSR in Node without tools like Next.js, Fresh or Astro you should import the path atomico/ssr/load
from the server
The @atomico/react package allows you to take advantage of support for SSR or SSG designed for React/Preact, example:
Next.js:
@atomico/astro allows to integrate SSR and SSG support to Astro build, We have used this integration to create the atomicojs.dev site.
Easily render webcomponents created with Atomico inside storytbook stories.
.storybook/preview.js
It facilitates the creation of stories, analyzing the components created with Atomico to automatically define the argTypes
and args
.
define also improves the declaration of stories by improving the autocompletion of these.
@atomico/vite
has exclusive storybook utilities, with these it seeks to facilitate the use of Atomico's JSX /TSX and live reload.
series of useful hooks for creating webcomponents
use-current-value
When creating design systems or component systems, we recommend that you maintain a centralized distribution structure in a single export package with multiple import paths, example:
Aesthetic coherence, the entire design system leverages itself and thanks to this we gain aesthetic coherence.
While a monorepo might seem like an ideal path, it actually increases the complexity of maintenance, whether it be component versioning and dependency maintenance.
We move faster and reduce implementation errors if you don't rely on individual versioning at the component level and leave this only defined at the design system level.
This has its pros and cons:
Pros:
It speeds up the creation of components, since it avoids the individual publication process and centralizes all this at the design system level.
Cons
you will not be able to update a component individually, since it is leveraged at the design system level.
you always prefer to keep each component isolated in a directory with names associative to the same component, example:
Share values from the scope via setter and getters
The useCurrentValue
hook allows associating a value with current
based on its parameter, equivalent to:
With the useCurrentValue
hook
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:
Increase the value before a click in a unit.
Increase the value by more than one unit according to the click pressure time.
why? The NPM-oriented packaging tool allows automatic export from the recommended structure,@atomico/exports
will generate a modern package.json to current standards, automatically generating all (main, types, exports and more) what is necessary for your package to be distributed correctly.
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
useRefectEvent will listen for the eventType of refFrom, to reflect it on refTo
Reflects on an element the given event
Retrieves the nodes assigned to a slot.
The usesClickCoordinates hook is for capturing click coordinates, this is useful when positioning a tooptip or creating visual effects
creates a bottleneck to the definition of a state, limits concurrency.
this hook is similar to useState, but the purpose of this hook is to bottleneck the state at update time
mode differences
fps:
if delay is set to 1, the update is executed for each cycle of requestAnimationFrame(60fps),
if delay is defined as 2, the update is executed for every 2 cycle of requestAnimationFrame(30fps)
timeout: the delay will be the milliseconds for setTimeout
idle : the delay will be the milliseconds for requestIdleCallback
Declare a state based on a responsive expression similar to using the tag img[srcset].
Where:
state
: String
, Current state according to the comparison between experiment and matchMedia.
expression
: String
, An expression that declares the serialized states.
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)
The following example shows the use of useResponsiveState, to display a message based on the mediaquery.
Communicate the component with external forms.
If the webcomponent is nested within a form tag, this hook will return that form tag as a reference.
If the webcomponent is nested within a form tag, you will be able to listen to events from that tag through useFormListener.
el hook renderiza un input hidden en el lightDOM cuyo name y value del input seran los parametros que el hook resiva
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
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:
All redirected hooks must exist under a slot
Create reactive templates that interact with the state of your webcomponent
Synchronize the state of the disabled prop with the fieldset tag
Inherit the disabled
status of a parent tag type fieldset
, under certain rules:
The label must be on the lightDOM.
The component that uses this hook must declare the prop {disabled: Boolean}
.
Where:
matches
: Optional string, allows to change the search of the parent tag fieldset for another tag or selector compatible with Element.matches.
Inject CSS into the shadowRoot
Inject tag style into shadowRoot with content given as parameter to use CSS.
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.
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.
Where :
channel
: String
, defines the name of the event to be used to generate the channel.
parentValue
: Value inherited by the parent component.
setChildValue
: Callback
, defines a value for nested components.
This hook is used by @atomico/components/router
Retrieve a node higher than the current webcomponent.
Where:
selector
: String
, Selector to be used by Element.matches when searching for the parent.
parent
: Element
, ascending search result according to selector.
Where:
parents:
parent nodes of the webcomponent
composed
: bypasses shadow DOM in parent capture.
Observe the size change of a reference.
Atomico makes it easy to build components with less code, better readability, and better reusability.
We invite you to discover part of the development experience you will get with Atomico:
Quick components to write since with Atomico you will require fewer lines of code to declare your webcomponents which will help you to be more productive
Fast in performance, since Atomico sends less code to the client, making your interface load quickly
This is thanks to a functional orientation inherited from React hooks plus some internal optimization from Atomic that ease the process of shaking the tree at compile time, achieving in this way sending the client a highly optimized JS that only has what you really use
This is thanks to Atomico's reliance on React hooks syntax plus the ability to completely eliminate the need for this when using webcomponents.
Atomic offers additional coverage for native behavior for React and Vue, allowing your component to be more embed-friendly, example React:
Atomico has a really efficient and simple type validation method, the type validation works in the following way:
the given value is transformed to the corresponding type, be it String, Number, Boolean, Array or Object, once transformed it is sent to the .
evaluates if the value is of the declared type:
If it corresponds to the type:
It is saved in props.
An event is emitted (if this has been configured in the prop).
It is reflected as an attribute (if this has been configured in the prop).
It is sent to the update queue and subsequent rendering.
It does not correspond to the type: an error is created by console with the following data:
target: Instance of the webcomponent.
value: Input value.
type: expected type.
Where:
const [state,setState]
: Return of useState
, the arguments allow reading and updating of the state associated with the hook instance.
state
: Current state.
setState
: Current status updater.
useState( optionalInitialState )
: Function that associates the state to the webcomponent:
optionalInitialState
: Optional parameter that defines the initial state associated to the hook instance, If optionalInitialState
is a function it will be executed in order to obtain the initial state only at the moment of the hook instance for the first time.
Atomico's virtualDOM is designed to enhance the use of webcomponents.
Atomico supports jsx-runtime, alternatively you can import the h
function to declare manual of the JSX pragma, eg:
An important rule of Atomico's virtualDOM is that every webcomponent must return the <host/>
tag since it represents the state of the webcomponent's DOM, such as:
Enable the use of the shadowDOM by declaring the shadowDom
property.
Association of events, attributes or properties.
Template of the webcomponent.
Atomico considers that a property must be associated as an event if it is of the function type and begins with the prefix 'on', eg:
the key property can receive values of the type of any type that allows generating a reference to the node, eg:
A technique inherited from React, it allows obtaining the reference of the node to which the Ref object is associated through the ref property, example:
This property allows you to declare the use of the shadowDom, eg:
You can declare a method by declaring a function in the host tag without using the prefix on in its name, eg:
If when creating or updating the DOM it does not detect the use of the property, it will be associated as a method of this, thus allowing it to be accessed from the DOM, eg:
rect
: Object
, the return of DOMRectReadOnly.toJSON()
, documentation of
Atomico supports the use of template-string thanks to the use of the package .
The references must be immutable objects, to create it there is the hook that creates a reference for each instance of the webcomponent.
To access the DOM safely wait for the resolution of the updated property created by the .
Force an update, ideal for working with references
Atomico makes it easy to declare events at the type level using the Host type.
In the previous code, we have declared the onMyCustomEvent
event at the type level. According to the template logic, this event will be dispatched every time the button is clicked, and the detail attached to this event will be of type CustomDetail
.
Where :
memoValue
: Return memorized by useMemo.
callback
: Function that is executed one or more times according to optionalArgumentList
.
optionalArgumentList
: Array of arguments that controls the execution of callback
, if an argument of optionalArgumentList
changes it will trigger that callback
is executed again.
Hook that allows you to memorize a callback so that it keeps its scope
Where:
memoCallback
: Return memorized by useCallback.
Working on this documentation...
Dispatch events from the webcomponent without referencing the context(this)
Where:
dispatchEvent: callback, dispatches the event from the webcomponent and allows defining the detail by receiving a first parameter
myEvent: string, name of the event to dispatch.
eventInit: optional object, event configuration.
The second parameter of useEvent
allows customizing the behavior of the even:
Meta-types allow you to define properties not covered by Atomico's Automatic support, such as:
Atomico allows the definition of methods from the host tag, this in order to share the scope with the methods (Functions) of the component, but this escapes the definition of types, to patch this we must use the Host type, this will allow us to validate the method from the JSX, TSX and the component instance.
, this will allow to use custom tag with association of events and more, example:
Advantages: The react team will take care of the coverage of this characteristic.
Disadvantages: (Optional) The maintainer of the component must declare the types of the custom tag.
Although the use of the custom tag is a way of instantiating the component, many times it does not define the import path at the time of its use, complicating the resolution of the component's origin, to avoid this we recommend the use of the Atomico wrapper for React.
Atomico the package allows:
Create a Wrapper component for the custom Element
Avoid react conflicts with webcomponents, such as association of events, attributes, properties and children.
Reflect the types declared in Atomic to React, valid for JSX or TSX
All webcomponents work in Next if it escapes from SSR
Remember if you use the auto
module, it should always be imported first than the customElement to use, otherwise auto
will generate an id as a custom tag to instantiate the component within react
Guide that defines some differences that exist between Atomico and React when working with the DOM.
Atomico's virtualDOM is:
Close to standard DOM .
Additional coverage to webcomponents.
Atomico does not support the use of functions to instantiate the component as we traditionally do in React, so that the component can be instantiated as a constructor it must be a webcomponent or a real Node.
Like React in Atomico you need to use the prefix on to announce an event, but there is a difference Atomico does not manipulate the name of the event so onClick
is different from onclick
, the purpose of this difference is to support custom events.
the key
property in Atomicoo can be of type String, Number, Symbol or other immutable reference.
Coverage is automatic if you decide to share your package using under the following
Type to structure a component from its creation
The declaration const myComponent: Component<Props, MetaProps>
defines at the Typescript level the types of props and other options with which the component should be structured.
This process is strict but makes autocompletion and error detection easier in the component declaration.
Some warnings that this type can create are:
The declaration of the prop in myComponents.props does not match the type declared in Props.
A props declaration is missing.
Props has invalid metadata, example reflect has been defined for a Promise type.
With Atomico, asynchrony is really easy thanks to the fact that they will allow you to know the status of the process or suspend the rendering of the component.
Atomico has 3 great hooks to solve asynchronous tasks:
usePromise: Processes asynchronous tasks and shows the status and resolution of these
useAsync: Allows you to pause rendering until a promise is resolved
useSuspense: Allows to know the paused states product of the use of useAsync nested in the component
component
: function that declares the webcomponent for Atomico.
VanillaElement
: class that will be extended by Atomico to create Component, Atomico will not break the life cycle of the component, allowing them to interact freely.
classes produced by the Atomico function c
, these can be extended between components, example:
Consider the following effects when using this inheritance model:
The render
will be rewritten.
The props
are inherited, Atomico will reuse the previously declared props.
Styles
are inherited. Atomico will merge the stylesheets.
The c
function creates an optimized standard custom element, which can be extended to modify its behavior, be:
Adding methods.
Creating or replacing style sheets.
Creando nuevas propiedades.
Suppose we have a MyButton
product of the function c
, we can extend this component to modify its appearance without the need to completely rewrite it, example:
The benefit of this inheritance is to simplify the modification of the appearance of a component created with Atomico, since it avoids its rewriting.
Here are some tips you can take into account when creating webcomponents with Atomico
Write the functional component using the first lowercase character, since the functional declaration is not instantiable as a constructor in JSX.
This prevents confusion when identifying the constructor of the component instance.
preferably use useProp in the following cases:
By modifying the prop from inside the component.
By isolating the logic of the prop in a customHook.
In most cases downloading the prop from the first argument of the function is simpler and more declarative, example:
This does not rule out the use within the style tag, since it is sometimes the solution to the definition of conditional styles or variables to the logic and outside the scope of the custom properties.
The usePromise hook consumes an asynchronous function is ideal for using fetch or other asynchronous tasks.
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.