---
title: Svelte
slug: wip/svelte
createdAt: 2024-07-25T12:21:32.415Z
---

# Svelte

## Supported Versions

- Svelte 4+
- TypeScript 5+

Cosmos Web Components are custom elements built using StencilJS, designed to be framework-agnostic and highly performant. This guide provides steps to integrate Cosmos web components into a Svelte application.

## Installation

:::hint{type="warning"}
Cosmos uses Red Bull's custom fonts to display text content inside components for different languages.Please follow the guide for [Font Faces](https://cosmos.redbull.design/wip/font-faces) to learn more about the different ways to provide them.
:::

Cosmos Web Components are available through Red Bull's proprietary npm registry. Access to this registry requires setting up an `.npmrc` file in the project root with the propert authentication details.

Add the following lines to the `.npmrc` file:

:::CodeblockTabs
.npmrc

```none
@cosmos:registry=https://artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/
//artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/:_auth=cy1yYm1oLXJlYWRvbmx5LXJiZHM6QVA4bTJXZVNhN2Q5bTZYVUpIcVZmdGtTOGpR
//artifactory.redbullmediahouse.com/artifactory/api/npm/rbds-npm-local/:always-auth=true
```
:::

*Note: The provided authentication token is public and read-only.*

To install the Cosmos, run:

```shell
npm install @cosmos/web
```

## Basic Usage

Cosmos Web Components need to be registered with the browser's Custom Element Registry. This is done by invoking the `defineCustomElements` function from the loader module.

:::CodeblockTabs
main.ts

```typescript
import App from "./App.svelte";
import { defineCustomElementCosmosButton } from "@cosmos/web";

defineCustomElementCosmosButton();

const app = new App({
  target: document.getElementById("app")!,
});

export default app;
```
:::

Once defined, you can use the components in your Svelte components as you would any native HTML element.

:::CodeblockTabs
App.svelte

```typescript
<cosmos-button>Click Me!</cosmos-button>

```
:::

### Properties

Properties can be passed to a web component using attribute binding or property binding.

:::CodeblockTabs
App.svelte

```typescript
<script lang="ts">
  const selectedCountries = ['AT', 'DE'];
</script>

<cosmos-select
  value={selectedCountries}
  help-text="Select one or more countries."
  label="Countries"
  multiple
  name="countries"
  placeholder="Pick a country"
>
  <cosmos-option value="AT">
    <cosmos-flag slot="prefix" code="AT"></cosmos-flag>
    Austria
  </cosmos-option>
  <cosmos-option value="DE">
    <cosmos-flag slot="prefix" code="DE"></cosmos-flag>
    Germany
  </cosmos-option>
  <cosmos-option value="CH">
    <cosmos-flag slot="prefix" code="CH"></cosmos-flag>
    Switzerland
  </cosmos-option>
</cosmos-select>
```
:::

### Slots

Cosmos Web Components can have named and unnamed slots for content insertion.

:::CodeblockTabs
App.svelte

```typescript
<cosmos-badge shape="pill">
  <cosmos-icon-label slot="prefix"></cosmos-icon-label>
  Snowboarding
</cosmos-badge>
```
:::

### Events

Custom events emitted by Cosmos Web Components can be listened to using Svelte's `on:event` directive.

:::CodeblockTabs
App.svelte

```typescript
<script lang="ts">
  let cosmosInputRef: HTMLCosmosInputElement;
  
  function handleInputChange(event: CustomEvent<{ value: string }>) {
    console.log('Input changed:', event.detail.value);
  }
</script>

<cosmos-input
  bind:this="{cosmosInputRef}"
  label="Name"
  name="name"
  placeholder="Max"
  required
  required-label="Required"
  validation-message="Please input your name"
  on:inputchange="{handleInputChange}"
></cosmos-input>
```
:::

:::hint{type="info"}
�&#xDCA1;**&#x20;Pro Tip**

When using TypeScript, it's important to note that `event.target` refers to the actual custom element. It might be necessary to typecast the event target for stronger typing.
:::

:::hint{type="info"}
�&#xDCA1;**&#x20;Pro Tip**

Although Cosmos Web Components - derived from the `HTMLElement` interface - can handle native DOM events, they might not always be the most semantic choice. Custom events are designed to propagate actions to the semantic elements housed within the component's shadow DOM.

When faced with similar behaviors between native and custom events, always opt for custom events.
:::

### Methods

Public methods on a Cosmos Web Component can be called by obtaining a reference to the component and then calling the method.

:::hint{type="warning"}
**☝️ Watch out**

Be mindful of the asynchronous nature of public methods and ensure that the component is defined before attempting to call them.
:::

:::CodeblockTabs
App.svelte

```typescript
<script lang="ts">
  let cosmosInputRef: HTMLCosmosInputElement;

  async function checkInputValidity() {
    if (cosmosInputRef) {
      const isValid = await cosmosInputRef.inputCheckValidity();
      console.log('Input validity:', isValid);
    }
  }
</script>

<form on:submit|preventDefault={checkInputValidity}>
  <cosmos-input
    bind:this={cosmosInputRef}
    label="Name"
    name="name"
    placeholder="Max"
    required
    required-label="Required"
    validation-message="Please input your name"
  ></cosmos-input>
  <cosmos-button type="submit">Submit</cosmos-button>
</form>
```
:::

## Common Issues to Avoid

### Differences from Native Elements

While Cosmos Web Components may share names with native HTML elements, their APIs may differ. Always refer to component-specific documentation to verify behaviors.

### Self-closing Tags

Custom elements require explicit closing tags, unlike some HTML elements that use self-closing tags.

```html
<!-- ✅ Correct -->
<cosmos-input></cosmos-input>

<!-- ❌ Incorrect -->
<cosmos-input />
```

## Need More Details?

Please refer to individual component documentation for a complete API overview.
