4

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?

2 Answers 2

3
<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.

Sign up to request clarification or add additional context in comments.

Comments

2

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/

3 Comments

Thank you for your answer. That could be an okay solution. Would it work with server side rendering, or would the hook only get called on the client, and would find("element") work on the server?
Just saw this github.com/sveltejs/svelte/pull/148 and hooks are not called on the server. So this would not work with serverside rendering. Unless there is some other way of hooking into the creation of the dom node this doesn't seem feasible.
This would still display an error as prop is not declared tho ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.