> To build or manage a Wix site with an AI agent, follow https://www.wix.com/headless/skill.md
> It builds a new Wix site or puts your own site online, from a prompt, and keeps changing it afterwards. The pages are code in any web technology, and Wix runs the backend.
> It works through the Wix plugin (the Wix MCP and the Wix skills), the Wix CLI or no Wix login, and puts the site live on Wix hosting or on another host.
> Business features include a store, bookings, events and tickets, a restaurant, a blog, forms, members and many more.
> Read the Wix skills online at https://www.wix.com/skills
> 
> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - If a reference page seems to be missing its schema (parameters, return types, or type definitions), append `?schema=true` to its `.md` URL (e.g. `https://dev.wix.com/docs/contexts/contexts/stores/category-info/use-category-info-context.md?schema=true`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Custom Element Extension Files and Code

## Article: Custom Element Extension Files and Code

## Article Link: https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/site/custom-elements/custom-element-extension-files-and-code.md

## Article Content:

# Custom Element Extension Files and Code

[Add a new custom element extension](https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/site/custom-elements/add-a-custom-element-extension-with-the-wix-cli.md) to your CLI project with the [generate](https://dev.wix.com/docs/wix-cli/cli-for-apps/command-reference/project-commands/generate.md) command, select **Custom Element** as the framework.

The CLI generates a folder with the name you choose, containing the following files:

+ An `element.extension.ts` file that defines a builder containing the configuration settings for your custom element.
+ An `element.tsx` file that contains the main code for the custom element.
+ A `element.panel.tsx` file that contains the code for your widget's settings panel.
+ A `element.module.css` file that configures CSS styling to customize your widget's appearance. It's generated with some initial styles to help you get started.
+ A default thumbnail image in your project's `public/` folder, named `<element-name>-thumbnail.png`. It's the thumbnail displayed in the **Add Elements** panel and the **Manage Apps** page for your widget. This file is optional, but without a thumbnail, your widget won't appear in the [Add Elements panel or the Manage Apps page](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-widgets/display-a-site-widget-in-the-add-panel-and-site-dashboard.md).

![Custom element in add elements panel](https://wixmp-833713b177cebf373f611808.wixmp.com/images/bc25d688c71ae039fb00aa037d436140.png)

It's possible to create each of these files yourself, but we don't recommend it for a couple of reasons:

+ You're more likely to make errors in the filepath if you add the files and folders yourself. If the filepath is incorrect, the CLI can't detect the custom element and it won't work.
+ The auto-generated files offer template code that helps you get started developing.

## element.extension.ts

The `element.extension.ts` file configures the settings for how your custom element appears on a user's site. This file is required, so don't delete it after the extension is generated. If you add your own files, you must include `element.extension.ts`.

When you generate a new custom element in your project, you'll see the following code in `element.extension.ts`:

```typescript
import { extensions } from '@wix/custom-extensions';

export default extensions.customElement({
  id: 'b24a8688-e25f-478f-9cb0-45b0008d6404',
  name: 'My Element',
  width: {
    defaultWidth: 450,
    allowStretch: true
  },
  height: {
    defaultHeight: 250
  },
  installation: {
    autoAdd: true
  },
  presets: [
    {
      id: 'e2ead1f8-6ba6-4f24-9610-696d16527ea7',
      name: 'default',
      thumbnailUrl: '{{BASE_URL}}/my-element-thumbnail.png',
    },
  ],
  tagName: 'my-element',
  element: './extensions/site/widgets/my-element/my-element.tsx',
  settings: './extensions/site/widgets/my-element/my-element.panel.tsx',
});
```

You can edit the configuration object and add properties as follows:

| Key                            | Type     | Description                                                                                                                                                                                                                                                                                                                                |
|----------------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `id`                             | string   | A unique identifier for your custom element. The CLI generates this GUID for you. If you add the JSON file yourself, you must generate your own GUID.                                                                                                                                                                                          |
| `name`                           | string   | The name of the custom element as it appears in the [app dashboard](https://manage.wix.com/account/custom-apps). The CLI prompts you for the name when you create the extension.                                                                                                                                                                              |
| `height.defaultHeight`           | number   | The widget's height in pixels when it is first installed on a site.                                                                                                                                                                                                                                                                    |
| `width.defaultWidth`             | number   | The widget's width in pixels when it is first installed on a site.                                                                                                                                                                                                                                                                     |
| `width.stretchByDefault`         | boolean  | Whether to stretch the widget to full width on installation.                                                                                                                                                                                                                 |
| `width.allowStretch`             | boolean  | Whether to allow users to toggle the widget between full-width and default width.                                                                                                                                                                                                                                   |
| `installation.autoAdd` | boolean | Whether the widget is automatically added to the site home page when your app is installed. If `false`, the widget isn't added upon install. |
| `presets[0].id `        | string  | A unique GUID identifier for the preset object containing your thumbnail.  |
| `presets[0].name`        | string  | The display name for the preset. The CLI sets it to `default`. You can change it to any descriptive name.  |
| `presets[0].thumbnailUrl`        | string  | The URL path to your thumbnail image. Use the format `{{BASE_URL}}/your-image-name.png`, where `your-image-name.png` is the filename of your image in the `public` folder. Don't include `public` in the path. The CLI sets it to `{{BASE_URL}}/<element-name>-thumbnail.png`.  |

Set `installation.autoAdd` to `true` to automatically add the widget to the site home page when the app is installed. Wix users can move the widget to any location after installation. If it's `false`, the widget isn't added on installation and Wix users can add the widget manually from the editor's **Add** panel. In the CLI, automatic installation applies only to the home page. For details, configuration examples, and best practices, see [About custom element installation with the CLI](https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/site/custom-elements/about-custom-element-installation-with-the-cli.md).

## element.tsx

The `element.tsx` file is where you write the code for the custom element. You can write code in other files and include it here, but you must export your custom element from this file. This is where the CLI looks for the custom element definition.

This file is required for the custom element to work, so don't delete it. If you add the files on your own, you must include `element.tsx`.

When the `element.tsx` file is generated, it looks like this:

```javascript
class MyElement extends HTMLElement {
  static get observedAttributes() {
    return ['display-name'];
  }

  constructor() {
    super();
  }

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback() {
    this.render();
  }

  render() {
    const displayName = this.getAttribute('display-name') || `Your Widget's Title`;

    this.innerHTML = `
      <div style="font-size: 16px; padding: 16px; border: 1px solid #ccc; border-radius: 8px; margin: 16px; height: 50%;">
        <h2>${displayName}</h2>
        <hr />
        <p>
          This is a Custom Element generated by Wix CLI.<br />
          Edit your element's code to change this text.
        </p>
      </div>
    `;
  }
}

export default MyElement;
```

The file defines a class called `MyElement` that extends `HTMLElement`. The class renders the `display-name` attribute that the generated settings panel sets. It lists `display-name` in `observedAttributes`, so the browser calls `attributeChangedCallback()` and the element re-renders whenever that attribute changes. The file exports the class so Wix can work with it.

The generated element code doesn't use `element.module.css`. It sets inline styles instead. The React example in this section imports the CSS module.

You don't need to call `define()`. Wix defines the custom element for you.

To write the element in React instead, wrap your React component with [`reactToWebComponent()`](https://www.npmjs.com/package/react-to-webcomponent) and export the result. For example:

```javascript
import React, { type FC } from 'react';
import ReactDOM from 'react-dom';
import reactToWebComponent from 'react-to-webcomponent';
import styles from './element.module.css';

interface Props {
  displayName?: string;
}

const CustomElement: FC<Props> = ({
  displayName = `Your Widget's Title`,
}) => {
  return (
    <div className={styles.root}>
      <h2>{displayName}</h2>
    </div>
  );
};

const customElement = reactToWebComponent(
  CustomElement,
  React,
  ReactDOM as any,
  {
    props: {
      displayName: 'string',
    },
  }
);

export default customElement;
```

## element.panel.tsx

The `element.panel.tsx` file contains the code defining your custom element's settings panel. The settings panel lets site users customize the widget after they install your app. 

In the panel's code, use Wix's [JavaScript SDK](https://dev.wix.com/docs/sdk.md) to [access widget properties](https://dev.wix.com/docs/sdk/host-modules/editor/widget/introduction.md) and [retrieve environmental data from the editor](https://dev.wix.com/docs/sdk/host-modules/editor/info/introduction.md), as well as access and manage Wix business solutions.

To apply changes made in the settings panel to the widget, call the [`setProp()`](https://dev.wix.com/docs/sdk/host-modules/editor/widget/set-prop.md) method in the Widget API. Widget properties are bound to your custom element's attributes, so any change in the properties automatically updates the corresponding attribute. How your custom element responds to an updated attribute depends on how you wrote `element.tsx`:

+ A class that extends `HTMLElement`, like the generated code: List each attribute your custom element responds to in `observedAttributes`, and handle updates in `attributeChangedCallback()`. The browser calls `attributeChangedCallback()` only for attributes listed in `observedAttributes`. The generated code in the `element.tsx` section uses both `observedAttributes` and `attributeChangedCallback()`.
+ React code with `reactToWebComponent()`: You don't need to write [`attributeChangedCallback()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#responding_to_attribute_changes), because `reactToWebComponent()` handles attribute updates for you. For each prop in the `props` option, `reactToWebComponent()` reads the matching kebab-case attribute and passes the attribute's value to your React component as that prop, converted to the type you declare. For example, `widget.setProp('display-name', newDisplayName)` updates the `display-name` attribute, and the component re-renders with the new value in its `displayName` prop. To add a widget property, add a prop to your component and to the `props` option with its type. Then call `widget.setProp()` with the property's kebab-case name.

When writing multiple properties from the panel, serialize writes and confirm each value with [`getProp()`](https://dev.wix.com/docs/sdk/host-modules/editor/widget/get-prop.md) before the next write. See [Create a Settings Panel for a Site Widget or Plugin](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/create-a-settings-panel-for-a-site-widget-or-plugin-wix-cli-and-self-hosting.md) for an example.

After the custom element is generated, you'll see code like this in `element.panel.tsx` file:

```typescript
import React, { type FC, useState, useEffect, useCallback } from 'react';
import { widget } from '@wix/editor';
import {
  SidePanel,
  WixDesignSystemProvider,
  Input,
  FormField,
  SectionHelper,
} from '@wix/design-system';
import '@wix/design-system/styles.global.css';

const SITE_WIDGETS_DOCS = 'https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/site/custom-elements/about-custom-element-installation-with-the-cli';.md

const Panel: FC = () => {
  const [displayName, setDisplayName] = useState<string>('');

  useEffect(() => {
    widget.getProp('display-name')
      .then(displayName => setDisplayName(displayName || `Your Widget's Title`))
      .catch(error => console.error('Failed to fetch display-name:', error));
  }, [setDisplayName]);

  const handleDisplayNameChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const newDisplayName = event.target.value;
    setDisplayName(newDisplayName);
    widget.setProp('display-name', newDisplayName);
  }, [setDisplayName]);

  return (
    <WixDesignSystemProvider>
      <SidePanel width="300" height="100vh">
        <SidePanel.Content noPadding stretchVertically>
          <SidePanel.Field>
            <FormField label="Display Name">
              <Input
                type="text"
                value={displayName}
                onChange={handleDisplayNameChange}
                aria-label="Display Name"
              />
            </FormField>
          </SidePanel.Field>
        </SidePanel.Content>
        <SidePanel.Footer noPadding>
          <SectionHelper fullWidth appearance="success" border="topBottom">
            Learn more about <a href={SITE_WIDGETS_DOCS} target="_blank" rel="noopener noreferrer" title="Site Widget docs">Site Widgets</a>
          </SectionHelper>
        </SidePanel.Footer>
      </SidePanel>
    </WixDesignSystemProvider>
  );
};

export default Panel;
```

The file contains a React component called `Panel` that defines the custom element's settings panel with the following key features:

1. **State Management**: Uses React hooks (`useState`, `useEffect`, `useCallback`) to manage the display name property.
2. **Widget Integration**: Uses the `widget` API from `@wix/editor` to get and set widget properties.
3. **UI Components**: Utilizes Wix Design System components like `SidePanel`, `Input`, and `FormField` for a consistent user interface.

As with `element.tsx`, you can write code in other files and include it here, but you must return your main component in this file. The panel code must be written in React to work with the rest of the CLI.

Learn more about [creating a settings panel for a custom element](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/create-a-settings-panel-for-a-site-widget-or-plugin-wix-cli-and-self-hosting.md). You can also [integrate Wix's native color and font pickers in your panel](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-widgets/integrate-wix-s-native-color-and-font-pickers-in-a-site-widget-s-settings-panel.md).

## Custom element thumbnail

The CLI adds a thumbnail image to your project at `public/<element-name>-thumbnail.png`. The preset in `element.extension.ts` references it as `{{BASE_URL}}/<element-name>-thumbnail.png` in `thumbnailUrl`. This thumbnail displays in the **Add Elements** panel.

To use your own image, replace the generated file with an image of the same name. Or add a new image to the `public` folder and update `thumbnailUrl` to match.

<blockquote class="important">

**Important:**
If you rename the thumbnail file, you must update the path in `thumbnailUrl`. Without a thumbnail, your widget won't appear in the [Add Elements panel or the Manage Apps page](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/site-widgets/display-a-site-widget-in-the-add-panel-and-site-dashboard.md).

</blockquote>