In svelte, I’m currently templating out an array of messages like this:
{#each messages as message, i}
{@const isLast = i === messages.length - 1}
<div class="card" class:active={isLast}>
{message}
</div>
{/each}
I then have a function where I can append a new item to the array
function addNextWord(){
messages = [...messages, words[index]];
}
When I do so, I’d like to scroll the very last item into view (using something like Element.scrollIntoView).
But how can I get a reference to just the last item in the loop?
Demo in Svelte REPL
>Solution :
Just use an action.
const initialCount = messages.length;
const scroll = node => {
if (messages.length > initialCount)
node.scrollIntoView()
}
<div class="card" use:scroll ...
In the vast majority of cases actions are just better than bind:this.