Skip to content

Conditional bind:this (allow undefined and conditional targets) #4570

@dkzlv

Description

@dkzlv

Is your feature request related to a problem? Please describe.

It has a lot of possible applications. Here's the latest problem I faced today.

I have a big paginated list, that has page buttons in the bottom of the list, and I want to scroll the list to the first item whenever I change the page. I want to use scrollIntoView method, so I need a ref to the first item of the list.

Describe the solution you'd like

It seems to be quite safe to allow undefined as a possible value for ref — it would just mean to not bind this element/component to any variable.

{#each arr as item, index}
  <p bind:this={index === 0 ? ref : undefined}>{item}</p>
{/each}

It also seems legit from developer point of view to allow dynamic ref target with code like this:

{#each arr as item, index}
  <p bind:this={cond(item) ? ref : ref2}>{item}</p>
{/each}

Describe alternatives you've considered
Right now I do this in multiple ways.

Array of refs. REPL. In two words:

<script>
  let refs = [];
</script>

{#each arr as item, index}
  <p bind:this={refs[index]}>{item}</p>
{/each}

and then use refs[0] or refs[refs.length - 1] to get certain elements.

I think:

  1. it is confusing
  2. it might have performance implications with huge lists
  3. it can even break business logic, because if your array gets smaller over time you'll end up with a bunch of null values in it. REPL

Custom class name. Assign a conditional class via class:custom-name={index === 0}, and then use document.querySelector to get the element with this class. It is bad because of two reasons: class name clashes (need to come up with unique name) and class name duplication (one in <script> and one in layout).

How important is this feature to you?
Not that much, it just seems like a good feature to have. I'm not aware of the internals of Svelte, but I assume adding any kind of dynamic code in element binding would be a lot of pain, because it most probably happens during compile time and not in the runtime.

Additional context
Same ideas were mentioned in this comment.

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