Components

Webflow Components are customizable blocks created from Elements. They serve as the backbone for structuring visual hierarchies on a Webflow site, ensuring that designs are modular, reusable, and consistent.

A Card Component

Definitions

Component Operations

With Component concepts explained, here is a quick overview of the capabilities offered by the Components API:

Create a Component Definition

To create a component definition you’ll need a root element - or top-level element - that has child elements within its element hierarchy. With the root element identified, you can use webflow.registerComponent(rootElement) to register the component definition. In the above card component example, the root element would be the container DIV element, which has the img, div, and button as child elements.

1// Get selected element
2const rootElement = await webflow.getSelectedElement();
3
4if (rootElement) {
5
6 // Create a component from the Root Element
7 const component = await webflow.registerComponent('MyCustomComponent', rootElement);
8 console.log(`Component registered with ID: ${component.id}`);
9
10} else {
11 console.log("No element is currently selected. Please select a root element first.");
12}

Edit a Component Definition

To make changes to a component definition, its component instance must be present on the page. You’ll then need to get the Component Instance, and use the enterComponent method to focus Webflow on the component definition. Once the component definition is in focused, you can get the root element of the component, and then insert / remove child elements from the root element.

1enterComponent: async () => {
2 // Step 1: Fetch the currently selected element
3 const selectedElement = await webflow.getSelectedElement()
4
5 if (selectedElement && selectedElement.type === 'ComponentInstance') {
6 // Step 2: Enter the context of the selected ComponentElement
7 await webflow.enterComponent(selectedElement as ComponentElement)
8 console.log('Successfully entered the component context.')
9
10 // Step 3: After entering the component's context, fetch the root element
11 const rootElement = await webflow.getRootElement()
12 if (rootElement) {
13 // Check if element supports child elements
14 if (rootElement?.children) {
15 // Append newElement as a child to of the selected element
16 const newElement = await rootElement?.append(webflow.elementPresets.DivBlock)
17 console.log('Added new child element:', newElement)
18 } else {
19 console.log('Root element does not support child elements')
20 }
21 } else {
22 console.log('No root element found in this component context.')
23 }
24 } else {
25 console.log('The selected element is not a ComponentElement.')
26 }
27}

Add a Component Instance to a Page

Use webflow.createInstance(componentDefinition) to add a component instance to the page. Component instances can be nested as part of element hierarchies, including under other component instances.