Search code examples
svelte

Add class to svelte component


I created two components:

1. btn.svelte

<button class="btn" />

2. btnHold.svelte

<script>
    import Btn from './btn.svelte';
</script>

I'm trying to add a new class btn--hold to btn.svelte

<Btn class="{btn} btn--hold" />

I get an error on class.

Basically I would like in the end to have:

<button class="btn btn--hold" />

How can I add a class to an imported component?


Solution

  • class is protected keyword, you can work around that by changing the name like this:

    <script>
        // ...
        let className = '';
        export { className as class };
    </script>
    
    <button class="btn {className}" ...
    

    Usage example (btn class is already added internally):

    <Btn class="btn--hold" ...