user2419993
user2419993

Reputation: 43

Automatically passing html attributes to svelte components

Is it not possible to allow svelte components to automatically apply all regular html attributes to the top most element within the component?

Component.html

<div>
  <slot></slot>
</div>

Application.html

<div>
  <Component class="extend">
    Some text
  </Component>
</div>

And have the .extend added to the div inside the Component?

Upvotes: 4

Views: 3884

Answers (2)

Rehan H
Rehan H

Reputation: 314

<Widget {...$$props}/>
<input {...$$restProps}>

It's possible but not recommended. Straight from the docs: https://svelte.dev/docs

$$props References all props that are passed to a component, including ones that are not declared with export. It is not generally recommended, as it is difficult for Svelte to optimise. But it can be useful in rare cases – for example, when you don't know at compile time what props might be passed to a component.

Upvotes: 3

Andrew Smith
Andrew Smith

Reputation: 1841

Because you can have multiple top level items in a component, this would not be possible. However you could do something similar to what I have outlined in this blog post for Ractive. You would have to make sure you are setting only 1 top level item per component though.

https://www.donielsmith.com/blog/2016/06/05/passing-attributes-down-with-ractivejs/

Upvotes: 2

Related Questions