Header Ads Widget

How to pass data from Child to Parent Component and vice-versa in LWC (lightning web component)?

In Lightning Web Components (LWC), communication between child and parent components can be achieved using various techniques. Here are two commonly used methods to pass data from child to parent and vice versa:

  1. Parent-to-Child Communication (Passing Data to Child):

    Parent JavaScript code
    // Todos Component      
    import { LightningElement } from 'lwc';
    
    export default class Todos extends LightningElement {
      todoList = [
      	{id: 1, name: 'Pay bill'}, 
        {id: 2, name: 'call plumber to fix water issue'}
      ];
      
    }
          
    
    Parent HTML Code
    <template for:each={todoList} for:item="todo">
    <todo-item
    key={item.id}
    todo={item.todo}
    ></todo-item>
    </template>

    In the above example, Todos (html template) runs a for-loop and render todo-item component inside it by passing todo (object) to it. todo-item component can recieve data by using @api decorator. Check the child component (TodoItem) example

    // TodoItem (child component)      
    import { LightningElement, api } from 'lwc';    
    export default class TodoItem extends LightningElement {
      @api todo; // data received from parent
    }
        
  2. Child-to-Parent Communication (Passing Data from Child to Parent Component):

    In the above example we have already seen how to pass data from Parent component to Child Component, Now in this example we will see how to pass data from child to parent component.

    Parent JavaScript code
    // Todo Component      
    import { LightningElement } from 'lwc';
    
    export default class Todos extends LightningElement {
      todoList = [
      	{id: 1, name: 'Pay bill'}, 
        {id: 2, name: 'call plumber to fix water issue'}
      ];
      
      handleDelete(event) {
        const todoId = event.detail.id;
        if (todoId) {
          this.todoList = 
          this.todoList.filter(todo => todo.id !== Number(todoId));
        }
      }
    
      handleComplete(event) {
        const todoId = event.detail.id;
        const completed = event.detail.checked;
    
        if (todoId) {
          this.todoList = this.todoList.map(todo => {
            if (todo.id === Number(todoId)) {
              return { 
              	...todo, 
                completed, 
                completedClass: completed ? 'completed' : '' 
              };
            }
            return todo;
          });
        }
      }
    }    
        
    Parent HTML Code
    <template for:each={todoList} for:item="todo" for:index="index">
    <todo-item
    key={todo.id}
    todo={todo}
    oncomplete={handleComplete}
    ondelete={handleDelete}>
    </todo-item>
    </template>


    Child JavaScript code
    // TodoItem Component      
    import { LightningElement, api } from 'lwc';
    
    export default class TodoItem extends LightningElement {
      @api todo; // data received from parent
      
      handleDelete(event) {
        const todoId = event.target.dataset.id;
        
        // dispatch event to parent with detail object
        this.dispatchEvent(new CustomEvent('delete', {
            detail: {
                id: todoId,
            }
        }));
      }
    
      handleComplete(event) {
        const todoId = event.target.dataset.id;
        const checked = event.target.checked;
        
        // dispatch event to parent with detail object
        this.dispatchEvent(new CustomEvent('complete', {
            detail: {
                id: todoId,
                checked: checked,
            }
        }));
      }
    }    
        
    
    
    Child HTML Code
    <template>
    <input type="checkbox" data-id={todo.id} onchange={handleComplete} />
    <span class={todo.completedClass}>{todo.name}</span>
    <button data-id={todo.id} onclick={handleDelete}>Delete</button>
    </template>

Post a Comment

0 Comments