HowTo add another component on button click

Viewed 225

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 Answers

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]}

Related