Reputation: 119
Is it possible to use a store variable in Svelte as class name?
Tried this, but it doesn't work:
export const classNameForSvg = writable('iconWrapper')
<div class={`${$classNameForSvg}`} bind:offsetWidth={width} use:inView>
Would be a super simple way of switching between classnames..
Upvotes: 0
Views: 1042
Reputation: 734
Is 'div' supposed to be a component, not just a normal HTML div? If so, it won't pass onto the component element class unless you specify. I am sure this is the reason as I wouldn't bind anything to DIV unless it is a component. Make sure your component supports:
// this is a child component
<script>
...
let classNames;
export { classNames as class };
...
</script>
<div class={classNames}>
</div>
<script>
import {writable} from 'svelte/store'
export const classNameForSvg = writable('iconWrapper')
</script>
// this is the parent view
<MyIconComponent class={$classNameForSvg} bind:offsetWidth={width} use:inView/>
If it isn't a component, I am sure attaching what classname it returns will be very much helpful.
Upvotes: 1
Reputation: 7741
You might have forgotten the :global()
modifier? The template string is not neccessary, simply class={$classStore}
is enough (the store value is a string), then it works REPL
<script>
import {writable} from 'svelte/store'
const className = writable('class-one')
</script>
<div class={$className} on:click={() => $className = 'class-two'}>
Div with changing class
</div>
<style>
:global(.class-one) {
background: lightblue;
}
:global(.class-two) {
background: lime;
}
div {
padding: 3rem;
}
</style>
Upvotes: 2