Skip to content

Less verbose way to pass through props into components? #8029

Closed as not planned
@davjhan

Description

@davjhan

Describe the problem

When creating games with svelte, its very common to create "Sprite" components. For example, if I wanted to create a resizable textbox, with a fancy drag handle (e.g. a small knob that appears when hovering on a corner), it could look something like this.

<ResizeableTextbox>
  ...
  <DragHandle/> // top left
  <DragHandle/> // top right
  <DragHandle/> // bottom left
  <DragHandle/> // bottom right
  ...
</ResizeableTextbox>

I want the <DragHandle> component to only encapsulate the fancy rendering of the knob, and not to contain any behavior/control logic. Also, since I use tailwind, I want to be able to apply style overrides via classes.

If <DragHandle> was an element, I could simply do:

<ResizeableTextbox>
  ...
  <div class='...' use:draggable > </div> // Assume 'draggable' is a custom svelte action.
  <div class='...' use:draggable > </div>
  <div class='...' use:draggable > </div>
  ...
</ResizeableTextbox>

But since it's a component, I have to explicitly declare the props in the DragHandle.svelte component and manually pass it along to the root element.

// DragHandle.svelte
<script>
  export let action
  let klass
  export { klass as class }
</script>
<div class='... {klass}'  use:action>
   ...
</div>

I'd like to see some way to reduce this boilerplate that needs to be repeated for every component that I want to use as a 'Sprite'. More generally, for tailwind users, allowing the extension of the class of the root element in a component is a pretty frequent pattern.

Describe the proposed solution

I don't have a clear solution, but here are some ideas to get the brainstorm ball rolling:

  1. A new attribute on elements that inherits all the props of the component?
// DragHandle.svelte
<div passthrough >
  ...
</div>
  1. Introduce some kind of way to do inheritance in svelte components.
    Discussed already in issue 192.

Alternatives considered

1. Wrap the Component in a div and apply the styles on the div.

<ResizeableTextbox>
  ...
  <div class='...' use:draggable >
    <DragHandle/>
  </div>
  ...
</ResizeableTextbox>

Cons: Creates an unnecessary div. Doesn't allow full flexibility as the node of the actions applied refer to the wrapper div and not the sprite.

2. Create sprites as a custom element

Cons: The cons of custom elements are in the svelte docs.

Importance

would make my life easier

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions