OmaRosh
OmaRosh

Reputation: 63

Svelte: How to pass data or props from a child component to the parent?

I'll try to be brief. I'm having the main component app.svelte. Inside it I'm using a child component called Course.svelte. I'm using an {#each} block to repeat the same component many times. The thing is I want the app.svelte to know whenever a single component is on:clicked. Right now I'm handling the on:click event in the Course.svelte component. And like this, App.svelte won't ever know about it. What should I do?

A snippet of Course.svelte and how I'm handling the on:click event:

<script>
  function handleClick() {
    if (state == courseStates.CLOSED) {
      //Handle closed course
    } else {
      if (state === courseStates.READY) {
        passCourse();
      } else if (state === courseStates.PASS) {
        failCourse();
      }
    }
  }
  function passCourse() {
    state = courseStates.PASS;
  }
  function failCourse() {
    state = courseStates.READY;
  }
</script>

<div on:click={handleClick} class="text-center course btn {buttonClass}">
  <h1>{name}</h1>
  <h4>{code} - {credit} Credit Hours - Term {term}</h4>
</div>

A snippet of App.svelte where I want to maintain the state of each course as it changes over time by clicking the course:

<div class="row">
    {#each courses as course}
      {#if course.term == term}
        <Course
          state={course.state}
          name={course.name}
          credit={course.credit}
          term={course.term}
          code={course.code}
          on:removecourse={removeCourse} />
      {/if}
    {/each}
  </div>

Upvotes: 6

Views: 7671

Answers (1)

grohjy
grohjy

Reputation: 2149

You can use two-way data binding by adding App.svelte bind:state={course.state}. Now the value in App.svelte will be updated if the value is changed in Course.svelte.

Here is a REPL:
https://svelte.dev/repl/48649794a7144d63bbde67a2db2f67a9?version=3.24.1

There are a much better ways to handle this problem and you should be careful when to use two-way binding. With two-way binding you’ll mess your dataflow very easily.

Better ways to handle dataflow:

  • Pass a function from parent to child
  • Pass the whole data-object to child component
  • Use store
  • Use custom events createEventDispatcher

Upvotes: 11

Related Questions