-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Description
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:
- it is confusing
- it might have performance implications with huge lists
- 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.