AnmolPlayzz
AnmolPlayzz

Reputation: 23

Adding classes to components in SvelteKit

I am trying to make a navbar in sveltekit

The issue I am facing with the method I chose to use is that it gives me the error:

Classes can only be applied to DOM elements, not components

Here's my code for reference

<IconButton sveltekit:prefetch
   class:active={url !== "/"
    ? currentPage.match(url)
    : url === currentPage}
    href={url}>
    
    <TextBlock variant="bodyStrong">
        {name}
    </TextBlock>
</IconButton>

IconButton is a component from the third party lib called fluent-svelte

Upvotes: 1

Views: 3162

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9939

According to the source code for fluent-svelte's IconButton (lines 12-14 & 40), you can pass a class prop that is subsequently applied to the underlying a or button element. Any additional props other than class, href, disabled or element will also be passed through to the underlying a or button element, as stated by the documentation for IconButton.

However, you cannot use the Svelte class:name directive on IconButton as that type of directive is indeed restricted to DOM elements.

But you could easily reproduce that directive's behavior:

<script>
    const active = url !== "/"
        ? currentPage.match(url)
        : url === currentPage
</script>

<IconButton
    sveltekit:prefetch
    class={active ? 'active' : ''}
    href={url}
>
// ... your svg code here
</IconButton>

and the active class will get conditionally applied to the underlying button or a element.

Upvotes: 4

Related Questions