Skip to content

Feature Suggestion: Improve versatility of <svelte:component> and <svelte:element> by treating them as a <svelte:fragment> when the this prop value is present but is a falsy or nullish value #7437

@brandonmcconnell

Description

@brandonmcconnell

Describe the problem

In some cases, I would like to conditionally render some content in a component or element.

Describe the proposed solution

For these cases, it would be useful if we were able to conditionally omit the component or element by using a nullish or falsy value in the this prop. So this example (below) would simply render Some text since the this prop is a falsy value:

<svelte:component this={false && MyComponent}>
  Some text
</svelte:component>

In such cases, the <svelte:component> or <svelte:element> would simply be treated as a <svelte:fragment>.

Alternatives considered

The main alternative is see is similar but essentially creating my own Fragment component which simply returns the slotted content in this format:

<slot {...$$restProps} />

In practice, it could be used like this:

<svelte:component
  this={condition
    ? WrapperComponent
    : Fragment
  }
>
  Some text
</svelte:component>

The downside to this, aside from having to import another custom component is that it would not work at all for <svelte:element>. In those cases, I would actually have to create a Svelte component counterpart for every single element so I could use them against my new Fragment component like this:

<script>
  import { Fragment, Div } from './customComponents.js';
  const condition = Math.random() < 0.5;
</script>

<svelte:component
  this={condition
    ? Div
    : Fragment
  }
>
  Some text
</svelte:component>

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions