WFComponent
WFComponent
serves as the driving force behind xAtom's reactivity, enabling the transformation of Webflow elements into dynamic and interactive components. With WFComponent
, you gain mastery over various aspects, including styling, text updates, attribute control, CSS classes, and event listeners (e.g. onclick
and onchange
). As the pivotal class within the xAtom framework, WFComponent
, initiated by a selector query, propels your web development endeavors into dynamic realms. ✌️
Getting Started
Initialization: To unlock the immense potential of WFComponent
in your xAtom project, begin by creating a new WFComponent
instance. Provide a valid selector as an argument to the class constructor. For instance:
import { WFComponent } from "@xatom/core";
// Create a new WFComponent instance for the first element with the CSS class ".btn"
const myComponent = new WFComponent(".btn");
Control and Customize: Once myComponent
is initialized, you gain precise control over styling, text updates, attribute management, CSS classes, and event listeners for all elements matching the specified selector. Customize and fine-tune your myComponent
to seamlessly align with your project's unique requirements.
Explore Additional Initialization Methods
// Initialize WFComponent using different selectors
const buttonA = new WFComponent("#button");
const buttonB = new WFComponent(".button");
const buttonC = new WFComponent(`[xa-type="button"]`);
const buttonD = new WFComponent(`.buttons > button`);
// Benefit from TypeScript type support
const container = new WFComponent<HTMLDivElement>(`.mydiv`);
These examples illustrate various methods to create WFComponent
instances using different CSS selectors. The last example showcases how to leverage TypeScript type support when initializing WFComponent
for specific Webflow elements. Feel free to explore these options to best suit your project's needs. 💡
Selector Parameter
The selector
parameter within WFComponent
is versatile and can accept one of the following types:
- A string that precisely matches a valid CSS selector.
- An HTMLElement representing a specific element in the document.
- An existing
WFComponent
instance.
If the provided string is not a valid CSS selector, it will result in an exception. You can learn more about CSS selectors here
// Example: Initialize WFComponent with a CSS selector
const myComponentBySelector = new WFComponent(".btn");
// Example: Initialize WFComponent with an HTMLElement
const myDiv = document.getElementById("myDiv");
const myComponentByElement = new WFComponent(myDiv);
// Example: Initialize WFComponent with an existing WFComponent instance
const existingComponent = new WFComponent(".existing");
const myComponentByInstance = new WFComponent(existingComponent);
This provides insights into the flexibility of the selector parameter, allowing developers to initialize WFComponent using various supported types, enhancing its adaptability in different scenarios. 🎯
Methods
The WFComponent
class offers a comprehensive set of properties and methods to empower your development journey:
getElement()
Obtain the underlying HTML element linked to the WFComponent
instance, granting you access to native HTML element APIs for extended functionality.
// Create a new WFComponent instance for a <div> element
const container = new WFComponent<HTMLDivElement>(`.mydiv`);
// Retrieve the associated HTML element
const htmlElement = container.getElement();
// Now, harness the full power of native HTML element APIs
console.log(htmlElement);
Syntax
getElement() : HTMLElement;
With getElement()
, you can seamlessly integrate custom behavior into your web components beyond the scope of xAtom.
setAttribute(key,value)
Assign a specific attribute to the element by specifying the attribute key and its corresponding value.
// Create a new WFComponent instance for an input element
const input = new WFComponent(`.myinput`);
// Set a native HTML attribute as an example
input.setAttribute("disabled", "disabled");
// Define a custom attribute with a key and value
input.setAttribute("xa-type", "my-btn");
Syntax
setAttribute(key:string,value:string) : void;
Parameters
Name | Type | Description |
---|---|---|
key | string | The attribute key to be set. |
value | string | The value to assign to the attribute. |
getAttribute(key)
Returns the value of the attribute with the specified key.
// Create a new WFComponent instance for an link element
const link = new WFComponent(`.mylink`);
// Get the value of the attribute
const hrefValue = input.getAttribute("href");
console.log(hrefValue);
Syntax
getAttribute(key:string) : string;
Parameters
Name | Type | Description |
---|---|---|
key | string | The attribute key to retrieve. |
hasAttribute(key)
Checks if the element has the attribute with the specified key.
// Create a new WFComponent instance for an input element
const input = new WFComponent(`.myinput`);
// Check if the attribute is present
const isDisabled = input.hasAttribute("disabled");
console.log(isDisabled);
Syntax
hasAttribute(key:string) : boolean;
Parameters
Name | Type | Description |
---|---|---|
key | string | The attribute key to check. |
removeAttribute(key)
Removes the attribute with the given key from the element.
// Create a new WFComponent instance for an input element
const input = new WFComponent(`.myinput`);
// Remove the attribute
input.removeAttribute("disabled");
Syntax
removeAttribute(key:string) : void;
Parameters
Name | Type | Description |
---|---|---|
key | string | The attribute key to remove. |
getChildAsComponent(selector)
Returns the first matched child element under the current parent element as a WFComponent instance.
// Create a new WFComponent instance for a card component
const card = new WFComponent(`.my-card`);
// Create a new WFComponent instance for a link inside the card
const cardLink = card.getChildAsComponent(`.my-link`);
Syntax
getChildAsComponent<T>(selector:string) : WFComponent<T>;
Parameters
Name | Type | Description |
---|---|---|
selector | string | The CSS selector. |
getChildAsComponents(selector)
Returns an array of matched children elements under the current parent element as WFComponent instances.
// Create a new WFComponent instance for a product listing element
const productList = new WFComponent(`.product-listing`);
// Create an array of WFComponent instances for all product cards inside the listing
const productCards =
productList.getChildAsComponents(`.product-card`);
productCards.forEach((productCard) => {
console.log(productCard);
});
Syntax
getChildAsComponents<T>(selector:string) : WFComponent<T>[];
Parameters
Name | Type | Description |
---|---|---|
selector | string | The CSS selector. |
getManyChildAsComponents(selector)
Returns matched children elements under the current parent element based on the provided object of selectors as WFComponent instances.
// Create a new WFComponent instance for a product card
const productCard = new WFComponent(`.product-card`);
// Define an object with selectors for various child elements
const selectors = {
img: ".product-img",
title: ".product-title",
price: ".product-price",
};
// Get the specified child elements within the product card
const { img, title, price } =
productCard.getManyChildAsComponents(selectors);
console.log(img, title, price);
Syntax
getManyChildAsComponents(selector:{[key:string]:string}) : {[key:string]:WFComponent};
Parameters
Name | Type | Description |
---|---|---|
selector | Object | An object containing key-value pairs for naming variables in the return and their associated CSS selectors. |
getCssClass()
Returns an array containing all the CSS classes present in the element.
// Create a new WFComponent instance for a button
const button = new WFComponent(`.btn`);
const cssClasses = button.getCssClass();
console.log(cssClasses); // Outputs: ["btn", "btn-primary", "small"]
Syntax
getCssClass() : string[];
addCssClass(className)
Adds the specified CSS class to the element.
// Create a new WFComponent instance for a button
const button = new WFComponent(`.btn`);
// Append the CSS class
button.addCssClass("btn-primary");
const cssClasses = button.getCssClass();
console.log(cssClasses); // Outputs: ["btn", "btn-primary"]
Syntax
addCssClass(className:string):void;
Parameters
Name | Type | Description |
---|---|---|
className | string | The CSS class name |
replaceCssClass(oldClassName,newClassName)
Replaces the old CSS class with the new CSS class on the element.
// Create a new WFComponent instance for a button
const button = new WFComponent(`.btn`);
console.log(button.getCssClass()); // Outputs: ["btn", "btn-primary", "small"]
// Replace the CSS class
button.replaceCssClass("btn-primary", "btn-secondary");
console.log(button.getCssClass()); // Outputs: ["btn", "btn-secondary", "small"]
Syntax
replaceCssClass(oldClassName:string,newClassName:string):void;
Parameters
Name | Type | Description |
---|---|---|
oldClassName | string | The old CSS class name to replace |
newClassName | string | The new CSS class name to set |
toggleCssClass(className)
Toggles the presence of the specified CSS class on the element.
// Create a new WFComponent instance for an accordion element
const accordion = new WFComponent(`.accordion`);
console.log(accordion.getCssClass()); // Outputs: ["accordion", "opened"]
// Toggle the CSS class
accordion.toggleCssClass("opened");
console.log(accordion.getCssClass()); // Outputs: ["accordion"]
accordion.toggleCssClass("opened");
console.log(accordion.getCssClass()); // Outputs: ["accordion", "opened"]
Syntax
toggleCssClass(className:string):void;
Parameters
Name | Type | Description |
---|---|---|
className | string | The CSS class name to toggle |
removeCssClass(className)
Removes the specified CSS class from the element.
// Create a new WFComponent instance for a dialog element
const dialog = new WFComponent(`.dialog`);
console.log(dialog.getCssClass()); // Outputs: ["dialog", "opened"]
// Remove the CSS class
dialog.removeCssClass("opened");
console.log(dialog.getCssClass()); // Outputs: ["dialog"]
Syntax
removeCssClass(className:string):void;
Parameters
Name | Type | Description |
---|---|---|
className | string | The CSS class name to remove |
setStyle(style)
Updates the element's style by applying the provided style object.
// Create a new WFComponent instance for a accordion element
const accordion = new WFComponent(`.accordion`);
accordion.setStyle({
height: "300px",
//You can use variables as well
"--my-variable": "10px",
});
Syntax
setStyle(style:styleProperties):void;
Parameters
Name | Type | Description |
---|---|---|
style | Object | An object containing CSS styles or valid CSS variables. |
getStyle()
Returns the style object associated with the element.
// Create a new WFComponent instance for an accordion element
const accordion = new WFComponent(`.accordion`);
accordion.setStyle({
height: "300px",
"--my-variable": "10px",
});
// Retrieve the style object for the accordion element
const accordionStyle = accordion.getStyle();
// Output the style object to the console
console.log(accordionStyle); // Outputs: {..., height: "300px", "--my-variable": "10px", ...}
Syntax
getStyle():styleProperties;
on(eventType, fn)
Attaches an event listener to the element, listening for events such as 'click,' 'change,' or 'blur.'
// Create a new WFComponent instance for a button element
const button = new WFComponent(`.button`);
// Define a click event handler function
const onClick = () => {
console.log("Button clicked");
};
// Attach the click event listener to the button
button.on("click", onClick);
// Create a new WFComponent instance for an input element
const input = new WFComponent(`.my-input`);
// Define a change event handler function
const onChange = () => {
console.log("Input text changed", input.getAttribute("value"));
};
// Attach the change event listener to the input
input.on("change", onChange);
Syntax
on(eventType:string,(event:Event)=>void):void;
Parameters
Name | Type | Description |
---|---|---|
eventType | string | A case-sensitive string representing the event type to listen for. |
fn | function(event) | A callback function that is executed when the specified event type is triggered. |
off(eventType, fn)
Detaches an event listener from the current element.
// Create a new WFComponent instance for a button element
const button = new WFComponent(`.button`);
// Define a click event handler function
const onClick = () => {
console.log("Button clicked");
};
// Attach the click event listener to the button
button.on("click", onClick);
// Later, detach the click event listener
button.off("click", onClick);
Syntax
off(eventType:string,(event:Event)=>void):void;
Parameters
Name | Type | Description |
---|---|---|
eventType | string | A case-sensitive string representing the event type to detach. |
fn | function(event) | The callback function that was previously attached and should be detached from the specified event type. |
getText()
Returns the text content of the element.
// Create a new WFComponent instance for a heading element
const heading = new WFComponent(`.my-heading`);
// Get the text content of the heading
const textContent = heading.getText();
console.log(textContent); // Outputs: "Welcome to xAtom!"
Syntax
getText():string;
setText(text)
Updates the inner text of the element with the provided text.
// Create a new WFComponent instance for a paragraph element
const paragraph = new WFComponent(`.my-paragraph`);
// Update the inner text of the paragraph
paragraph.setText("Hello, xAtom!");
// Get the updated text
const updatedText = paragraph.getText();
console.log(updatedText); // Outputs: "Hello, xAtom!"
Syntax
setText(text:string):void;
Parameters
Name | Type | Description |
---|---|---|
text | string | The text to set as the inner text. |
getTextContent()
Returns the text content of the element.
// Create a new WFComponent instance for a span element
const span = new WFComponent(`.my-span`);
// Get the text content of the span
const spanTextContent = span.getTextContent();
console.log(spanTextContent); // Outputs: "Click me!"
Syntax
getTextContent():string;
setTextContent(text)
Updates the text content of the element with the provided text.
// Create a new WFComponent instance for a div element
const div = new WFComponent(`.my-div`);
// Update the text content of the div
div.setTextContent("This is some dynamic content.");
// Get the updated text content
const updatedTextContent = div.getTextContent();
console.log(updatedTextContent); // Outputs: "This is some dynamic content."
Syntax
setTextContent(text:string):void;
Parameters
Name | Type | Description |
---|---|---|
text | string | The text to set as the element's content. |
updateTextViaAttrVar(keyPair)
Enhance your web app's dynamism by updating text content based on configured xa-var attributes. This method checks for xa-var attributes on the element or its child elements and updates text accordingly using key-value pairs.
/**
* Example Product Card HTML structure:
* <div class="product-card">
* <div class="img-container"><img src="..." /></div>
* <h4 xa-var="title">Example title<h4>
* <p xa-var="description">Example description<p>
* <p xa-var="price">$0<p>
* <button ...>Add to cart</button>
* </div>
*/
// Create a new WFComponent instance for a div element
const productCard = new WFComponent(`.product-card`);
// Update text content with key-value pairs
productCard.updateTextViaAttrVar({
title: "Iced Americano",
description: "Bold and bitter coffee drink!",
price: "$5.00",
});
/**
* After text update, the Product Card will look like this:
* <div class="product-card">
* <div class="img-container"><img src="..." /></div>
* <h4 xa-var="title">Iced Americano<h4>
* <p xa-var="description">Bold and bitter coffee drink!<p>
* <p xa-var="price">$5.00<p>
* <button ...>Add to cart</button>
* </div>
*/
TODO: Webflow Screenshot
Syntax
updateTextViaAttrVar(keyPair:{[key:string]:string}):void;
Parameters
Name | Type | Description |
---|---|---|
keyPair | Object | An object containing variable names as keys and strings as values. |
getHTML()
Returns the HTML content of the element.
// Create a new WFComponent instance for a section element
const section = new WFComponent(`.my-section`);
// Get the HTML content of the section
const sectionHTML = section.getHTML();
console.log(sectionHTML); // Outputs: "<div class="content">...</div>"
Syntax
getHTML():string;
setHTML(htmlString)
Updates the inner HTML content of the element with the provided HTML string.
// Create a new WFComponent instance for a div element
const div = new WFComponent(`.my-div`);
// Update the inner HTML content of the div
div.setHTML("<p>This is <strong>bold</strong> text.</p>");
// Get the updated HTML content
const updatedHTML = div.getHTML();
console.log(updatedHTML); // Outputs: "<p>This is <strong>bold</strong> text.</p>"
Syntax
setHTML(htmlString:string):void;
Parameters
Name | Type | Description |
---|---|---|
htmlString | string | The HTML string to set as inner HTML. |
getCloneAsComponent()
Returns a clone of the current WFComponent as a new component instance.
// Create a new WFComponent instance for an element
const originalComponent = new WFComponent(`.my-element`);
// Clone the component
const clonedComponent = originalComponent.getCloneAsComponent();
Syntax
getCloneAsComponent():WFComponent<T>;
appendChild(child)
Appends the specified WFComponent
child element to the current element.
// Create a new WFComponent instance for a parent element
const parent = new WFComponent(`.parent`);
// Create a new child WFComponent element and clone child
const child = new WFComponent(`.child`).getCloneAsComponent();
// Append the child WFComponent element to the parent
parent.appendChild(child);
Syntax
appendChild(child:WFComponent):void;
Parameters
Name | Type | Description |
---|---|---|
child | WFComponent | The WFComponent child element to append. |
removeAllChildren()
Removes all children elements from the current element.
// Create a new WFComponent instance for a parent element
const parent = new WFComponent(`.parent`);
// Remove all children elements from the parent
parent.removeAllChildren();
Syntax
removeAllChildren():void;
remove()
Removes the element from the DOM.
// Create a new WFComponent instance for an element
const element = new WFComponent(`.my-element`);
// Remove the element from the DOM
element.remove();
Syntax
remove():void;