icarus
icarus

Reputation: 91

why button on:click does not work in svelte

I want to show a text input field whenever changeEmail is true. So I handleClick to set it to true. However, when I click on a button nothing happens. Would appreciate any help.

  let changeEmail = false;

 function handleClick() {
   console.log(changeEmail)
    changeEmail = !changeEmail;
  }
  $: changeEmail;
</script>

<div class="card">

  <div class="info-column">
    <h2>About</h2>
    <div class="info-field">
      <h4>Name</h4>
      {userModel.firstName} {userModel.lastName}
    </div>
    <div class="info-field">
      <h4>Email</h4>
      {#if changeEmail === false}
        {userModel.email}
      {:else}
        <TextInput placeholder="${userModel.email}"/>
      {/if}
      <Button on:click={handleClick}>Edit</Button>
    </div>
  </div>
</div>

this is a component that looks like this on page

<section>

  <PersonalSettingsCard userModel={$user}>

  </PersonalSettingsCard>
</section>

Upvotes: 5

Views: 6691

Answers (3)

ytyng
ytyng

Reputation: 715

If you use Svelte component on Astro SSR, You can set client:only="svelte" in your component tag.

<PersonalSettingsCard userModel={$user} client:only="svelte" />

Upvotes: 0

cascading-jox
cascading-jox

Reputation: 1131

Like H.B. said and wrote, the click event needs to be forwarded to the Button component. Here is an example in context from the tutorial (which I highly recommend completing if you haven't).

I also created a minimal REPL where the click event works with a custom <Button>.

Upvotes: 2

brunnerh
brunnerh

Reputation: 184376

If there are no errors (e.g. from userModel being null/undefined), the problem should be your Button component, using a native button element this will work just fine.

The component has to forward the event for it be usable outside.

<!-- In the Button component -->
<button on:click> ... </button>

Docs for on:event (see section after modifiers)

If the Button component comes from some library, you have to check what events are provided (though most would just forward click as one would expect).

Upvotes: 1

Related Questions