Components

What are Webflow Components?

Webflow Components are dynamic blocks of Elements, foundational to a Visual Developer & Marketer’s design process. They serve as the backbone for structuring visual hierarchies on a Webflow site, ensuring that designs are modular, reusable, and consistent.

Designers have embraced Webflow Components as their go-to tool for creating and managing reusable design "building blocks." These components empower Marketers and other Stakeholders to swiftly assemble sites that are not only visually appealing but also true to the brand's identity. Add to this the power of Variables, which allow for specific value assignments to terms. The result? A seamless design experience where site-wide changes are a breeze, and design consistency is maintained effortlessly.

What can I build?

The Components & Variables API is your gateway to pushing the boundaries of what Webflow Components can do. Think of crafting advanced, tailor-made components that integrate seamlessly with a site’s CMS, eCommerce settings, or even an existing style system. You have the potential to create components that not only fit into Webflow's design paradigm but also elevate it.

In this guide, we’ll walk you through using the Webflow object to create and delete Webflow Components and Instances in the Designer, as well as the Component object to read and write information about a Component. Together, we’ll successfully:

  • Create a Component
  • Create a Component Instance
  • Edit a Component
  • Delete a Component

Definitions, Instances, and Properties

Let’s review some key concepts of Components, and how they’re implemented in Webflow.

🟥 Component Definition

The blueprint or original design template for a Component. It establishes the foundational structure of Elements within the Component, as well as properties that can be further defined in a Component Instance. Any modifications made to the Component Definition will propagate and automatically update all associated Component Instances. This ensures consistency across instances while allowing for centralized changes.

🟦 Component Instance

A derivative or copy of the Component Definition. While it retains the core design and structure of the Definition, an Instance offers flexibility and customization through its Properties. Designers and users can give a Component Instance a custom value for a property without altering the original blueprint.

🟣 Component Properties

Pre-defined attributes within a Component Definition that can be assigned a specific value in the Component Instance. They allow designers or users to modify specific aspects of an Instance - text, images, links, and more - without affecting its foundational design.

❗️

Component Properties in Our APIs

As of v.2.0.0, our APIs do not support the creation and management of Component Properties. We understand the importance of this feature for our users, and we're excited to share that it's on our development roadmap. We're committed to enhancing our API capabilities and will provide updates as we make progress. Thank you for your patience and understanding!

Working with Components

Creating a Component

Using the webflow object, you can easily create a component. Simply assign your component a unique name and select an Element on the canvas to act as the Root Element. Any child elements of your chosen Root will automatically be incorporated into the component. Once successfully created, you'll find your new component in the Components Panel.

Example

const element = webflow.createDOM('div') // This can also be an existing native element
const component = await webflow.registerComponent('Hero-Component', element)

Errors

If a component with the same name already exists, the API will throw an error.

Uncaught (in promise) Error: Failed to register component Hero-Component. Is the name taken?

Creating a Component Instance

Once you’ve created your Component, you can render an instance of the Component on a page. A Component Instance is a copy of the main Component that renders as an Element on the Canvas. Any changes made to the main Component will be reflected in the Component Instance.

To add a Component Instance to the Canvas you must first define your Component. Additionally, you must set the Component Instance as a Child Element of a current Element on the page. ⏩ In the future, we plan to create the ability to set Component Properties in the Main cComponent, and specific property values in the instance.

Example

This code sample checks if a component exists, and then creates its instance.

// This is the name for our component
const myComponentName = "Hero-Component";

// Check if a component with this name exists
var componentDefinition = await getComponentByName(myComponentName);

// If a component by this name does not exist, create it
if (!componentDefinition) {
  const element = webflow.createDOM("div");
  const labelElement = webflow.createDOM("b");
  labelElement.setTextContent("This is a component");
  element.setChildren([labelElement]);
  componentDefinition = await webflow.registerComponent(
    myComponentName,
    element
  );
}

// Create a component instance
const heroComponentInstance = webflow.createInstance(componentDefinition);
const parent = await webflow.getSelectedElement();

// Append the component instance to the selected Element
parent.setChildren([...parent.getChildren(), heroComponentInstance]);
await parent.save();

// Check if component exists
const getComponentByName = async (componentName: string) => {
  const components = await webflow.getAllComponents();
  for (const c in components) {
    const currentComponentName = await components[c].getName();
    if (componentName === currentComponentName) {
      return components[c];
    }
  }
};

Editing a Component

To modify a Component, you first need to "focus" or "enter" it on the Canvas. When a component is in focus, all Globals pertain specifically to that Component, not the entire Site. For example, if you use the webflow.getAllElements() method while a component is in focus, it will retrieve all the Elements within that Component, rather than from the entire page.

Example

// Find a Component Instance
const elements = await webflow.getAllElements()
const componentInstance = elements.find(el => el.type === 'ComponentInstance')

// Enter into a Component Instance and get Elements within the Component
await webflow.enterComponent(componentInstance)
const elementsInComponent = await webflow.getAllElements()

// Example Response
[
    {"id": "e1638b63-8597-af77-e95c-8d4a4e3a7b01"},
    {"id": "e1638b63-8597-af77-e95c-8d4a4e3a7b02"},
    {"id": "e1638b63-8597-af77-e95c-8d4a4e3a7b03"}
]

Editing a component’s hierarchy - after entering a Component instance - allows you to change to the Component Definition, which will propagate these changes across all Component Instances

// Find a Component Instance
const elements = await webflow.getAllElements()
const targetInstance = elements.find(el => el.type === 'ComponentInstance' && el.getComponent().id === 'MyComponentId')

// Enter into a Component Instance
await webflow.enterComponent(targetInstance)

// Get Root Element
const root = await webflow.getRootElement()
if (root.children && root.configurable) { // Check if your Root Element can have children elements and is configurable   
root.setChildren([...root.getChildren(), someNewElements]) // Add Children to Root Element
await root.save() // Save Changes!

Once you're finished editing your Component Definition, exit the component.

await webflow.exitComponent()

Deleting a Component

To delete a Component, you’ll first need to delete all of its instances. Once you’ve removed all instances, you can unregister the Component from Webflow.

// Find all Instances of a Component and delete them
const elements = await webflow.getAllElements();
const componentInstances = elements.filter(
  (el) => el.type === "ComponentInstance"
);
componentInstances.forEach(async (el) => {
  if (el.type === "ComponentInstance") {
    let component = el.getComponent(); // Get Component Associated with Instance
    let componentName = await component.getName(); // Get Component Name
    let isMyComponent = componentName === myComponentName; // Check if it's the same component

    if (isMyComponent) {
      el.destroy();
    }
  }
});

// Delete Compnonent from Webflow
webflow.unregisterComponent(newComponent);

Methods

Set Name

setName(name: string): Promise<void>

Description: Set component name to the provided string. Components can be renamed, and the update happens immediately, without requiring an explicit save() invocation.

Returns: A Promise that resolves when the name change is successful.
await component.setName("She-ro Component")

Example:

await component.setName("She-ro Component")

Get Name

getName(): Promise<string>

Description: Get the name of a specific component.
Returns: A Promise that resolves to a string representing the name of a component.

Example

const myComponentName = "Hero-Component";
const components = await webflow.getAllComponents();

// Check if component exists
for (const c in components) {
  const currentComponentName = await components[c].getName();
  if (componentName === currentComponentName) {
    console.log("Found Hero Component");
  }
}