5

I am creating a data entry table. I wish to add a new row to the table when the AddRow button is clicked.

My structure is a <DataEntryForm> component with a <FormHeader> subcomponent and one or more <FormRow> subcomponents.

Here's my first newbie attempt:

let numRows = [1,1,1,1,1,1,1];

<div class='efContainer'>
   <FormHeader />
   {#each numRows as num}
      <FormRow />
   {/each}
</div>

<Button on:click={() => numRows.push(1)}>Add Row</Button>

On initial run, 7 rows are created as specified by the length of the numRows array initial value.

However, clicking the AddRow button does nothing (console logging shows that the array is being correctly updated. But of course nothing is telling the #each loop to re-run.)

  1. How should this app be restructured to make the AddRows button work?

  2. The numRows array seems a klunky way to manage creating new rows. Is there a more Sveltic way to do this?

1 Answer 1

5

You can refer to the Svelte tutorial on updating arrays and objects: https://svelte.dev/tutorial/updating-arrays-and-objects

Since numRows.push(1) never updates the value of numRows Svelte won't detect the change. An easy fix is to replace on:click={() => numRows.push(1)} with on:click={updateArray} where updateArray = () => {numRows = [...numRows, 1]}

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, so that was it. I forgot about the need to destructure and re-assign. Actually, this inline code worked: on:click={() => numRows = [...numRows, 1]} Many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.