Passing attributes to component DOM element
When you want to “forward” any attributes that you can’t control before compile time or that changes between each use of the component, like class
or style
, to your component wrapper DOM element (instead of declaring variables), use $$restProps
, like the code below. However, be aware that it isn’t generally recommended to use this approach, as it is difficult for Svelte to optimize it, since it doesn’t know how many atributes it will receive.
<!-- Component.svelte -->
<li {...$$restProps}><slot /></li>
<!-- App.svelte -->
<Component class="li-item-class">{name}</Component>
Svelte Playground here. See relevant part of docs for more.
This is helpful where, for example, using MDSveX, you want to create a bunch of Svelte wrappers to DOM elements like H1
, P
, and A
instead of the normal h1
, p
, and a
.
Note that when passing a class to component, you may need to set it to global :global(.title){...}