Add class to svelte component
Asked Answered
E

4

5

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?

Elizaelizabet answered 31/3, 2023 at 8:16 Comment(0)
M
12

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" ...
Marlenamarlene answered 31/3, 2023 at 8:50 Comment(2)
Thank you very much, it's working perfectly. Let me ask you one more thing, how can I add some text into that component like: <button>text</button> <Btn class="btn-hold" text />Elizaelizabet
Just define another property and interpolate it or use a slot. Have you done the tutorial?Marlenamarlene
C
10

In the btn.svelte component you can do:

<button class={ 'Btn ' + ($$restProps.class ?? '') } />
  • The $$restProps variable is an object of attributes which were passed to the component, but not explitly declared as props via the export let keyword.
  • I used the nullish coalescing operator ??, because if you don't pass the class attribute to the component, the result will be Btn undefined.

Now, in the btnHold.svelte component you simply do:

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

Working REPL here: https://svelte.dev/repl/c2b6625ed73144eeb6bebce6ea4a4d82?version=3.58.0

Caprification answered 31/3, 2023 at 13:33 Comment(2)
Are there any gotchas with this approach?Zackaryzacks
this is a much more sveltey approachRosewater
O
1

You could do it by exporting a className variable from the component, and adding it onto the button's existing class

  1. btn.svelte
<script>
    export let className;
</script>

<button class="btn {className}" />
  1. btnHold.svelte
<script>
    import Btn from './btn.svelte';
</script>

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

to add the btn--hold class to the button.

Otis answered 31/3, 2023 at 8:31 Comment(1)
As H.B. pointed out in a previous answer, 'class' a reserved keyword in Javascript so Svelte complier is going to give you an error if you try this. You'll need to use 'className' or some other appropriate identifier for your use case.Caiaphas
B
0

CustomButton.svelte:

<button class={$$props.class}>Custom Button</button>

App.svelte:

<script lang="ts">
    import CustomButton from "./CustomButton.svelte";
</script>

<CustomButton class="myStyle"/>
Bimestrial answered 13/4 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.