Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a CSS class based on a variable in Svelte

i am working on a custom component in Svelte and i want to be able to set the color with the help of corresponding identifiers(i callem types). For example success -> green, error -> red, etc.

Right now I am exporting a boolean for each of the "types" that can be set to true or false and therefore enables a class with the same name or not.

let success = false;
let error = false;
let info = false;
let warning = false; 
...
<div
    class:success
    class:error
    class:info
    class:warning >
</div>

This way the user would have to disable all but one of these types everytime he wants to change the type.

Is there a way i could do this similar like this almost pseudo code :D

export let type = "";
...
<div
    class:{type} >
</div>

So the User could then just use it the following way.

<custom-comp type={warning} />
like image 522
Snr Naldo Avatar asked Mar 04 '26 21:03

Snr Naldo


1 Answers

Use

class={type}

instead of:

class:{type}
like image 120
Snr Naldo Avatar answered Mar 07 '26 10:03

Snr Naldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!